% CLASS8OCT.M   Illustration of Newton's method and Secant method to solve
%   example equation    e^(-x) = x^2.5

% Define f(x) and plot it on the interval [0,1], where simple considerations
%   show there is a solution.  See:  p_0 = 0.5  is an o.k. initial guess.
disp('Plotting the problem,  f(x)=0,  in Figure 1.')
f = @(x) exp(-x) - x.^2.5;
x = 0:0.001:1;  plot(x,f(x)),  xlabel x,   grid on

disp('Newton method:')
dfdx = @(x) - exp(-x) - 2.5 * x.^1.5;
format long
p = 0.5, for n=1:10, p = p - f(p)/dfdx(p), end

disp('Secant method:')
% In class I did a loop-on-one-line, but here it is properly-formatted.
%   Unfortunately, division-by-zero occurs because function values
%   f(pold) and f(polder) become identical out to 15 digits.
polder = 0.5;
pold = 0.6
for n=1:10
  pnew = pold - f(pold)*(pold-polder)/(f(pold)-f(polder));
  polder = pold;
  pold=pnew
end

disp('Secant method with absolute tolerance 10^-14 stopping criterion:')
% To avoid division-by-zero, stop when successive estimates are close together.
%   In class we saw that I had to adjust the absolute tolerance all the way
%   "down" to 1.0e-7 before it really stopped earlier.
polder = 0.5;
pold = 0.6
for n=1:10
  pnew = pold - f(pold)*(pold-polder)/(f(pold)-f(polder));
  polder=pold;
  pold=pnew
  if abs(pold-polder) < 1.0e-14
    break
  end
end

