% Solve the nonlinear equation
%        x/(1-x^2) = 0
% using Newton's method.    This is to demonstrate that if f''(\xi) = 0, third
% order convergence is expected.

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

x = zeros(1,11);
order = zeros(1,11);
x(1) = 0.7;

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