function root= bisection(F,a,b,err)
% BISECTION
% Finds a zero of a real continuous function F(x) of a
% single real variable x in a given interval [a,b].
% Input arguments:
%        F   -  function handle;  a,b - ends of the interval;
%        err - tolerance (optional)
% Output argument:         x -  root 
% Normal input must satisfy conditions:
%    a<b;    err>0;  F(a)*F(b)<0.
%     Default  err  is  (b-a)/1e10
if  nargin<3,  error('Not enough input arguments'); end
if  nargin<4,  err=1.e-10*(b-a);    end
if  (err<=0),  error('err should be positive'); end
if (a>b),      error('a>b,  choose a correct interval'); end
vala = F(a);        valb = F(b); 
if vala*valb > 0,    error(' F(a) and F(b) are of the same sign'); end
% CALCULATIONS
while (b-a > err)
       root=(a+b)/2;  val=F(root); 
       if (val*vala>0)
              a=root;vala=val;
       else 
               b=root;valb=val;    
       end
 end
 root=(a+b)/2; 
 fprintf(1,'Root=%-16.8f\n',root);

 %=============================================================
 %>>my_f=@(x) exp(x)-2; z=bisection(my_f,0,1,1e-9);
 %Root=0.69314718      
 %>>format long;log(2)
 %ans =
 %   0.69314718055995
  %===============================================================
 %>> a=8;b=3;my_f=@(x) x^b-a;root= bisection(my_f,0,3,1e-7);