function NewtonVsSecant()
% Uses both Newton's method and the secant method to find a zero of
% f(x) = sin(x) near a given x0.

% Take this many steps...
nSteps = 8;

% A starting value...
x0 = 4;

% Generate the iterates and display...
xNewton = NewtonSteps(@sin,@cos,x0,nSteps);
xSecant = SecantSteps(@sin,x0,nSteps);
clc
disp(' k Newton Secant')
disp('-------------------------------------------------')
for k=1:nSteps
fprintf('%2d %18.15f %18.15f\n',k,xNewton(k),xSecant(k))
end

function x = NewtonSteps(f,df,x0,nSteps)
% f and df are function handles that reference a function of a single
% variable and its derivative.
% x0 is a starting value and x(k) is the kth Newton iterate, k=1:nSteps.

x = zeros(nSteps,1);
for k=0:nSteps-1
% Note that there is one f-evaluation and one df evaluation per step.
if k==0
% Guarding against a zero subscript...
x(k+1) = x0 - f(x0)/df(x0);
else
% The general step...
x(k+1) = x(k) - f(x(k))/df(x(k));
end
end

function x = SecantSteps(f,x0,nSteps)
% f is a function handle that reference a function of a single variable.
% x0 is a starting value and x(k) is the kth secant iterate, k=1:nSteps.

x = zeros(nSteps,1);
for k=0:nSteps-1
% Note that there is one f-evaluation per step (except step 0)
if k==0
% First step is finite difference Newton with divided difference
% parameter h ..
h = sqrt(eps);
fkm1 = f(x0-h)
fk = f(x0);
x(k+1) = x0 - fk/((fk - fkm1)/h);
fkm1 = fk;
elseif k==1
% Guarding against a zero subscript...
fk = f(x(k));
x(k+1) = x(k) - fk/((fk - fkm1)/(x(k)-x0));
fkm1 = fk;
else
fk = f(x(k));
x(k+1) = x(k) - fk/((fk - fkm1)/(x(k)-x(k-1)));
fkm1 = fk;
end
end