function [ x, ierror, k ] = steffenson ( x, abserr, kmax, f )

%*****************************************************************************80
%
%% steffenson() implements Steffenson's method.
%
%  Discussion:
%
%    Steffenson's method is of order 2.
%
%    x(n+1) = x(n) - f(x(n)) / g(x(n))
%
%    where
%
%    g(x) = ( f(x+f(x)) - f(x) ) / f(x)
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    15 May 2024
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Joseph Traub,
%    Iterative Methods for the Solution of Equations,
%    ISBN: 0828403120,
%    LC: QA297.T7.
%    Prentice Hall, 1964, page 178.
%
%  Input:
%
%    real X: the point that starts the method.
%
%    real ABSERR, an error tolerance.
%
%    integer KMAX, the maximum number of iterations allowed.
%
%    real external F, the name of the routine that
%    evaluates the function or its derivatives, of the form
%      function f ( x, ider )
%
%  Output:
%
%    real X: an approximate root satisfying abs ( F(X) ) < ABSERR.
%
%    integer IERROR, error indicator.
%    0, no error occurred.
%    nonzero, an error occurred, and the iteration was halted.
%
%    integer K, the number of steps taken.
%

%
%  Initialization.
%
  ierror = 0;
  k = 0;
  fx = f ( x, 0 );
%
%  Iteration loop:
%
  while ( true )
%
%  If the error tolerance is satisfied, then exit.
%
    if ( abs ( fx ) <= abserr )
      break;
    end

    k = k + 1;

    if ( kmax < k )
      ierror = 2;
      return
    end

    gx = ( f ( x + fx, 0 ) - fx ) / fx;

    if ( gx == 0.0 )
      ierror = 3;
      return
    end
%
%  Set the increment.
%
    dx = - fx / gx;
%
%  Update the iterate and function values.
%
    x = x + dx;
    fx = f ( x, 0 );

  end

  return
end
