% Solve the nonlinear equation
%        1+x-e^x = 0
% using Newton's method.  This is to demonstrate that if f'(\xi) = 0,
% locally only first order convergence can be expected.

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


x = zeros(1,101);
order = zeros(1,101);
x(1) = 1.;

fprintf('\nNewtons method \n');
fprintf('%10s    %12s           %12s\n', 'Iteration', 'Value', 'Order estimate');
fprintf('%10d    %.16f            -\n', 1, x(1));
for i=1:100
    x(i+1) = x(i) - (1+x(i)-exp(x(i)))/(1-exp(x(i)));
    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(1+x(i+1)-exp(x(i+1)))<1e-14)
       fprintf('Converged after %d iterations.\n', i)
       break;
   end
end