function c = bisection(funct, a, b, tolerance)

%Example file for bisection method with Tolerance. 
%Russell Brown, 13 September 2004. 

%funct is a function 
% a and b are endpoints of an interval
%Tolerance is the error we are willing to accept.


fa= funct(a);
fb = funct(b);
%check to see if we have a root. 
if ( fa == 0)
    c=a;
    return
end

if (fb == 0)
    c=b;
    return
end
%check to see if we have bad input. 
if (fa*fb>0)
    %error
    c=Inf;
    fprintf('Bad input.\n')
    return
end

%begin the bisection. 
while (abs(b-a)>=2*tolerance)
    
c = (a+b)/2;
fc = funct(c);

if (fc == 0) 
   
    return
end

if (fa*fc < 0)
    b=c;
    fb=fc;
else
    a=c ;
    fa=fc;
end

end %while

%we return the midpoint of the last value of the interval 
%if the function is continuous, this value is guaranteed to 
%be within tolerance of a root. 
c = (a+b)/2




