% Bisection method for root-finding
clear all; close all;

f=inline('x.^3-2*x-5','x'); % Define f as an inline function

eps = 1e-14; % define the tolerance (what happens if is too small?)
x1 = 2.0; x2 = 2.5; % Wide bracketing guesses taken from plot
xnew = x1+(x2-x1)/2; % Give xnew an initial value (not so important what it is)
step = 0; % Initialize step counter
while (abs(f(xnew))>eps) % Keep going till f(xnew) is REALLY small
    step = step + 1; 
    xnew = x1+(x2-x1)/2;
    disp([xnew; f(xnew)])
    error(step) = f(xnew);
    if (f(x1)*f(xnew) < 0)
        x2=xnew; % root is on left half of range
    else 
        x1 = xnew; % root is on right half of range
    end
end     
X = linspace(2.0,2.5);
figure(1); plot(X,f(X));
figure(2); semilogy(abs(error),'o:r') % Log plots don't work with negative data points
grid on                   % so we plot the absolute value of the error
xlabel('Number of bisections')
ylabel('|f(x_i)|')
title('Convergence of the bisection method for root-finding')
