function [ p, k ] = bisection( f, a, b, N, tol)
% Find a root of a function:
% f(x) = 0
% using the bisection method on the interval [a,b].
%
% Parameters:
% f: function handle
% a,b: interval
% N: maximum number of iterations
% tol: tolerance for accepting root.
% Check if end-points are roots
if( f(a) == 0 )
p = a;
k = 0;
return;
elseif( f(b) == 0 )
p = b;
k = 0;
return;
end
% Check if f(a) and f(b) have the same sign, throw an exception.
if ( f(a) * f(b) > 0 )
error( 'f(a) and f(b) do not have opposite signs' );
end
% Iterate N times unless a root is found
for k = 1:N
% 1) Calculate the mid-point
m = (a + b)/2;
% 2) Is the mid-point close enough to a root?
% Yes - Exit the loop.
% No - Keep looking for root
if ( f(m) == 0 || (b-a)/2 < tol )
p = m;
return;
% 3) Is root to the left of mid-point?
elseif ( f(m)*f(a) < 0 )
b = m;
% or to the right of the mid-point?
else
a = m;
end
end
error( 'Bisection method failed to converge' );