function [RootEstimate,Y] = newton(x,f,df,imax,tol) 
% This function estimates a singular root for equation 'f' from guess...
% 'x' using the Newton Raphson method. 
% Input: x initial guess at the root 
% f function to be evaluated 
% df derivative of f with respect to x 
% imax iteration maximum 
% tol convergence criterion 
% Output: estimation of the root position  
% Newton's algorithm 
% xnew = xold + dx 
% dx = -fold(xold)/dfold(xold) 
 
% initialise parameters:
x_next = inf;
diff = norm(x-x_next);
dfcheck = feval(df,x);
 
% CHECK: verify that the derivative is not zero. 
count=0; 
while diff>tol && count<=imax
    if dfcheck == 0           
        error('Problem');     
    end 

    f_at_guess = feval(f,x);
    dfdy_atfirst = feval(df,x);
    x_next = x - f_at_guess./dfdy_atfirst;
    diff=norm(x-x_next);

    count=count+1;     
    % calculate equation 4     
    fprintf(['\n Iteration: %i,\nError (10 d.p.): %.10f,\n'...
        'Root Estimate (10 d.p.): %.10f\n'],count,norm(x-x_next),x_next) 
    % CHECK: Excessive iterations 
    x = x_next;
end 
RootEstimate = x_next;
Y = f_at_guess;
end
