%
%   SECANT.M  Routine to implement the Secant Method
%
%   Inputs:  f   = function handle for user-supplied function.  
%                  The function f is of the form:  function y = f(x)
%          x0,x1 = two initial guesses for the root location
%            tol = convergence criterion  (tol > 100*eps)
%            M   = maximum number of iterations (M >= 2)
%        display = intermediate results are displayed if > 0                     .
%
%   Outputs:   x = estimated root of f(x) = 0 
%              k = number of iterations performed   (note that the number 
%                  of function evaluations is k + 2)
%   
%   File prepared by J. R. White, UMass-Lowell (last update:  Nov. 2017)
%
      function [x,k] = secant(f,x0,x1,tol,M,display)
%
%   check tolerance, # iterations, initial guesses, and display switch
      if tol < 100*eps,  tol = 100*eps;  end
      if M < 2,  M = 2; end
      if abs(x1-x0) < tol
         fprintf ('The Secant Method requires that x1 be different from x0.\n');
         return
      end
      if display > 0
        fprintf('\n\n Intermediate edit from the Secant Method:  \n\n');
        fprintf('    k       x0         f0         x1         f1         x2         f2\n');
      end
%
%   find root 
      f0 = f(x0);   f1 = f(x1);
      k = 1;   err = tol + 1;
      while (err > tol) && (k <= M)
        x2 = x1 - (x1-x0)*f1/(f1-f0);   f2 = f(x2);
        if display > 0
          fprintf('  %3i %10.6f %10.6f %10.6f %10.6f %10.6f %10.6f \n', ... 
                  k,x0,f0,x1,f1,x2,f2);
        end 
        err = abs(f2);   k = k + 1;
        x0 = x1;  f0 = f1;  x1 = x2;  f1 = f2;
      end
      x = x2;  k = k-1;   % save outputs
      if k == M 
        fprintf('\n\n  Warning: The maximum number of iterations was reached!!! \n');
      end
%
%   end of function

