
%   file name : newton.m

    function [p0,err,k,y]=newton(f,df,p0,delta,epsilon,max)

%      input 
%         f : the object function 
%         df : the derivative of f
%         p0 : the initial appoximation to a zero of f
%         delta : the tolerance for p0
%         epsilon : the tolerace for y 
%         max : the maximun number of iteration
%
%      output
%         p0 : the Newton approximation to the zero 
%         err : the error estimate for p0
%         k : the number of iteration
%         y : f(p0)


       for k=1 : max
           p1 = p0 - feval(f,p0)/feval(df,p0);
           err = abs(p1-p0);
           relerr = 2*err/(abs(p1)+delta);
           p0 = p1;
           y = feval(f,p0);
           if (err<delta) | (relerr<delta) | (abs(y)<epsilon)
               break
           end
       end


%   function info

    function y = fct(x)
       y = x*x - 8
    function y = df(x)
       y = 2*x


%----------------------------------------------------------------------

%     file name main.m
%     problem 
%        start with p0=3 and approximate sqrt(8)
%        by using Newton-Raphson method
%     newton.m  : having Newton algorithm and function info

%     input 
      p0 = 3;
      delta = 10^(-10);
      epsilon = 10^(-10);
      max = 50;

%     call 
      [p0,err,k,y]=newton('fct','df',p0, delta, epsilon, max);
      p0, err, k, y
      
