
function simpleNewton

% this m file finds p such that f(p)=0
% given an initial guess p0
% at the matlab prompt type: simpleNewton


fstring= 'x^2- 2';   % f(x)
dfstring= '2*x';     % derivative f(x)
p0=1.25;             % initial guess p0
eps=1.0e-6;          % set tolerance 
format long;         % digits in long format


eval(['x=p0;',fstring,';']);     % evaluate f  at p0
f = ans; 
eval(['x=p0;',dfstring,';']);    % evaluate f' at p0
df= ans;

%initialize errors
relerror=1000;
abserror=1000;
residual=1000;

while (abserror > eps)
    
  p=p0 - f/df;

  sprintf(['Approximate root is %-15.10f'],p)  %print p 
  
  %stopping criteria
  abserror=abs(p-p0);       % absolulte error
  relerror=abserror/abs(p); % relative error
  residual=abs(f);          % residual 
  
   
  %updates
  p0=p;
  eval(['x=p0;',fstring,';']);     % evaluate f  at p0
  f = ans; 
  eval(['x=p0;',dfstring,';']);    % evaluate f' at p0
  df= ans;
  
end % for loop   


if ( abserror > eps)
disp('fail to converge')
end % end loop


%print results
actualErr = abs(p - sqrt(2));  % |p_k - p| 
sprintf(['Approximate root of  x^2 - 2.0 is %-15.10f \n'],p) 
sprintf(['Error in    root of  x^2 - 2.0 is %-15.10e \n'],actualErr)






