function c = newton(f,df,p0,TOL,Max_it)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function c = newton(f,df,Tol,Max_it)
%
% Newton's Method
% finds root of function handle f i.e. solve f(x)=0
% f: function handle
% df: derivative of f
% p0: initial guess
% TOL: how close to root you want usually Tol = 1e-10
% Max_it: max # of iterations
% c: root
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


%f = @(x) x^3-x-3;
%df = @(x) 3*(x.^2)-1; 

%p0 = 1;

%Max_it = 100;
%TOL = 1e-12;
Err = zeros(1,1);

i = 1; %initialize counter

while i <= Max_it
    p1 = p0 - f(p0)/df(p0);
    Err(i) = abs(p1-p0);
    disp(['current iteration = ' num2str(i,'%03i') ' *** current error = ' num2str(Err(i),10)])
    %
    if abs(p1-p0)<TOL
        disp(['root via newton is = ' num2str(p1,20)])
        break
    end
    %
    if i == Max_it
        disp(['Method failed after N0 = ' num2str(i) ' iterations'])
        break
    end
    %
    i = i + 1;
    p0 = p1;
end

c = p1;
    


















