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

%*****************************************************************************80
%
%% hansen() implements the Hansen and Patrick method.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    15 May 2024
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Eldon Hansen, Merrell Patrick,
%    A Family of Root Finding Methods,
%    Numerische Mathematik,
%    Volume 27, 1977, pages 257 - 269.
%
%  Input:
%
%    real X, an estimate for the root of the equation.
%
%    real BETA, ???
%
%    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: if IERROR = 0, X is an approximate root for which
%    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 );
  dfx = f ( x, 1 );
  d2fx = f ( x, 2 );

  fprintf ( 1, 'hansen: %d  %g  %g\n', k, x, fx );
%
%  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

    z = dfx * dfx - ( beta + 1.0 ) * fx * d2fx;
    z = max ( z, 0.0 );

    bot = beta * dfx + sqrt ( z );

    if ( bot == 0.0 )
      ierror = 3;
      return
    end
%
%  Set the increment.
%
    dx = - ( beta + 1.0 ) * fx / bot;
%
%  Update the iterate and function values.
%
    x = x + dx;
    fx = f ( x, 0 );
    dfx = f ( x, 1 );
    d2fx = f ( x, 2 );

    fprintf ( 1, 'hansen: %d  %g  %g\n', k, x, fx );

  end

  return
end
