function xNew = Bisection(f, a, b, tol)
% Bisection(f, a, b, tol) calculates root of equation f(x)=0 bracketed by
% [a,b] using bisection method, with tolerance tol

fprintf('\n *** Bisection method solver *** \n\n');

if (f(a)*f(b) > 0)
   fprintf('Interval [%g,%g] does not bracket the equation root \n', a, b);
end

horzLine = '_________________________________________________';
fprintf(' n |        x(n)        |x(n)-x(n-1)|  f(x(n)) \n%s\n', horzLine);
xOld = a;

for n = 1:100
    xNew = (a + b) / 2;
    if ( f(xNew)*f(a) > 0 ) a = xNew;
    else b = xNew;
    end;
    
    fprintf('%2d | %18.12g | %9.2e | %9.2e \n', n, xNew, abs(xNew-xOld), f(xNew));  
    if  abs(xNew - xOld) < tol
        return
    end

    xOld = xNew;
end
fprintf('*** Bisection method failed to converge after 100 iterations');