% Solve the nonlinear equation
%        e^x-x-2 = 0
% using Newton's method.  This is to demonstrate that you may not have quadratic
% convergence for small k.


clear all;
clc;
exact = 1.1461932206205825; % exact solution
xx = 0:0.01:2;
ff = exp(xx)-xx-2.;
plot(xx,ff, '-k',  'Linewidth', 2);hold on;
plot(xx,0.*xx, '--r',  'Linewidth', 2);
legend('f(x)', 'y=0');
axis([0,2,-1,1]);


x = zeros(1,121);
order = zeros(1,121);
x(1) = 100.;

fprintf('\nNewtons method \n');
fprintf('%10s    %12s           %12s\n', 'Iteration', 'Value', 'Order estimate');
fprintf('%10d    %.16f            -\n', 1, x(1));
for i=1:120
    % different fixed point iterations
    x(i+1) = x(i) - (exp(x(i))-x(i)-2.)/(exp(x(i))-1.);
    if i < 2
        fprintf('%10d    %.16f    %10s\n', i+1, x(i+1), '-' );
    else
        order(i+1) = log(abs(exact-x(i+1))/abs(exact-x(i)))/log(abs(exact-x(i))/abs(exact-x(i-1)));
        fprintf('%10d    %.16f    %.10f\n', i+1, x(i+1), order(i+1) );
    end
    
    if (abs(exp(x(i+1))-x(i+1)-2.)<1e-14)
       fprintf('Converged after %d iterations.\n', i)
       break;
   end
end