﻿%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Written by Dr. Len Brin         15 January 2014 %
% Modified by Andy Long           6 February 2024 %
% Purpose: Implementation of Steffensen's method  %
% INPUT: function f; initial value x0; tolerance  %
%        TOL; maximum iterations N0               %
% OUTPUT: approximation x and number of           %
%        iterations i; or message of failure      %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [x,i] = steffensen(f,x0,TOL,N0)
  i=1;
  A=x0;
  B=f(A);
  while (i<=N0)
    x0=A;
    x1=B;
    x2=f(x1);
    if (abs(x2-x1)<TOL)
      x=x2;
%      disp(" ");
      return
    end%if
    x=x0-(x1-x0)^2/(x2-2*x1+x0);
%    disp(x);
    if (abs(x-x2)<TOL)
%      disp(" ");
      return
    end%if
    A=x;
    B=f(A);
    i=i+1;
  end%while
  x="Method failed---maximum number of iterations reached";
end%function
