% The bisection algorithm. 
% 2009-08-17, AK

% User input
f = inline('cos(pi*x)-1/2');

a = 0;
b = 1;
tol = 1.e-6;     % Accept the solution if b-a <= tol.
ftol = 1.e-12; % Accept the solution if |f(c)|<ftol. 

% Preparations
fa = f(a);
fb = f(b);

if fa*fb > 0
    error('The condition f(a)*f(b)<0 is not satisfied');
elseif abs(fa) <= ftol
    c = a;           % Accept c, 
    a = b - 10*tol;  % The main loop will not be executed. 
elseif abs(fb) <= ftol
    c = b;
    a = b - 10*tol; 
end

% Main loop 
while (b-a > tol) 
    c = (b+a)/2
    fc = f(c);
    if abs(fc)<=1.e-15
        break; 
    elseif fa*fc < 0
        b = c;
        fb = fc;
    else
        a = c;
        fa = fc;
    end
end

    
    
        
