%
%  Bisection method: find the root of cos(x) = x;
%          Victor Matveev Sep 16, 2014 

f = @(x) cos(x) - x;       % The function whose root we are calculating
a = 0;  b = pi / 2;        % Interval bracketing the root

epsilon = 1e-5;            % Accuracy that we desire
N = ceil( log((b - a) / epsilon) / log(2) ); % Number of steps needed 

for n = 1 : N
    c = (a + b) / 2;       % Bisect
    
    if  f(c)*f(a) > 0      % Compare sign(f(c)) with sign(f(a))
        a = c;             % If signs are the same, then a=c
    else
        b = c;             % If signs are diifferent, then b=c
    end;
    
    disp(['Step #', num2str(n), ': a=', num2str(a), ' b=', num2str(b), ' c=', num2str(c), ' f(c)=', num2str(f(c))]);
end
