% bisection.m
%
% Implements the bisection method based on the pseudo code
% `Bisection1', on page 94 of C&K.
%
% This code solves equation (1) of problem 1, problem set 1.
%
% You will have to change the parameters `a', `b', and the function `f'
% if you wish to solve the other problems.

a = 0;
b = 1;
nmax = 10;

u = a^3 - 3*a + 1;
v = b^3 - 3*b + 1;

if u*v > 0
   error('There may not be a root in the interval (a,b)');
end

for n = 1:nmax
   c = (a + b) / 2;
   w = c^3 - 3*c + 1;

   fprintf('n=%3d   c=%15.12f  f(c)=%9.2e\n', n, c, w)
   if abs(u * v) < eps
      break;
   elseif w * u < 0
      b = c;
      v = w;
   else
      a = c;
      u = w;
   end
end
