% Matlab script to illustrate the secant method
% to solve a nonlinear equation

% this particular script finds the square root of a number M
% (input by the user)

% note that the function we are trying to zero is f(x) = x^2 - M.
% this function is hard-coded in the script.

format long

% get user input
M = input('Please enter the number whose square root you want: ')
x0 = input('Please enter the first  of two starting guesses: ')
x1 = input('Please enter the second of two starting guesses: ')


% iteration counter
k = 1
% compute first secant iterate to enter loop
s = ( (x1^2-M) - (x0^2-M) ) / (x1 - x0);
x = x1 - (x1^2-M)/s
disp('Hit return to continue')
pause 

while abs(x-x1) > eps*abs(x),
    % reset guesses
    x0 = x1;
    x1 = x;
    % increment iteration counter
    k = k + 1
    % compute and display secant iterate
    s = ( (x1^2-M) - (x0^2-M) ) / (x1 - x0);
    x = x1 - (x1^2-M)/s
    disp('Hit return to continue')
    pause 
end