%
%  Math 340 * Victor Matveev * February 19, 2012
%  See solution to homework #4 for details
%
%  Problem 3.3.3: 
%  Secant 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);
	x0 = -1; x1 = 0;  
    k = 1;

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

end


