function newton()
% Newton's method for finding the root of x^3-2x-5 in [2,3]
%
  xn = 2.8;       % This is the initial condition
  maxit = 75;     % Allow a maximum of maxit iterations
  tol = 1.0e-8;   % Stop when |x_{n+1} - x_n| < tol
  err = Inf;      % Initial error
  iter = 0;       % Iteration counter
%
  fprintf(1, 'Iter         x_n                f(x_n)             f''(x_n)             Error        \n');
  fprintf(1, '----+-------------------+-------------------+-------------------+-------------------+\n');
%
  while iter < maxit && err > tol
     [fv, df] = f(xn);
     fprintf(1, '%4d %19.12e %19.12e %19.12e %19.12e\n', iter, xn, fv, df, err); 
     xnew = xn - fv / df;
     err = abs(xnew - xn);
     iter = iter + 1;
     xn = xnew;
  end
%
% Check for convergence
%
  if iter == maxit
     fprintf(1, '*** Newton iterations failed to converge in %d steps\n', maxit);
  else
     [fv, df] = f(xn);
     fprintf(1, '%4d %19.12e %19.12e %19.12e %19.12e\n', iter, xn, fv, df, err); 
     fprintf(1, 'Newton iterations converged in %d steps\n', iter);	
  end
%
end

function [fv, df] = f(x)
fv = x.^3 - 2*x - 5;
df = 3*x.^2 - 2;
end
