function root = newton(fname, x0, tol);

% NEWTON  Newton-Raphson method
%
% Input       fname  : Name of function.
%             x0     : First apoproximation of the root.
%             tol    : Relative error of the found root.
% Output      root   : Position of the root.
%
% Remarks  1) There are functions for which this method fails. So be very 
%             careful using this algoritm!
%          2) A disadvantage of this method is that you need the first
%             derivative of the function.

if nargin < 3, tol = 1e-7; end

oldroot = x0;

while 1,

% Calculate the new approximation based on the Newton-Raphson method

  [f,df] = feval(fname,oldroot);
  root = oldroot - f/df;

  err = abs((root-oldroot)/root);
  oldroot = root;
  if err < tol,
    break;
  end
end
