%
%  Math 340 * Victor Matveev * February 16, 2012
%  See solution to homework #4 for details
%
%  Problem 3.2.6: 
%  Newton's method for the root of f(x)=x + exp(-B*x^2)*cos(x)
%  B = 1, 5, 10

tolerance = 10^(-16); % Go for maximal accuracy

for B = [1 10 50]; 

    f = @(x) x+exp(-B*x.^2).*cos(x);
    dfdx = @(x) 1-exp(-B*x.^2).*(2*B*x.*cos(x)+sin(x));
    
    x0 = -0.2; 
    k = 1;

    fprintf('\n\n Newton''s method, B = %d:\n', B);
    fprintf(' iter #  |    Newton''s x_n     |  f(x_n) \n');
    fprintf('---------------------------------------------------\n');
    
    while dfdx(x0) ~= 0 && f(x0) ~= 0
        x1 = x0 - f(x0)/dfdx(x0);
        if abs(1 - x0/x1) < tolerance
            break;
        end;
        fprintf('    %d    | %.16f | %.3e \n', k, x1, f(x1) );
        x0 = x1;
        k = k + 1;
    end

end


