Halley's method for single-variable optimization

+- HP Forums (https://www.hpmuseum.org/forum)
+-- Forum: HP Software Libraries (https://www.hpmuseum.org/forum/forum-10.html)
+--- Forum: HP Prime Software Library (https://www.hpmuseum.org/forum/forum-15.html)
+--- Thread: Halley's method for single-variable optimization (/thread-23382.html)



Halley's method for single-variable optimization - Namir - 2025-04-07

The following HP Prime program performs single-variable optimization using Halley's method. To use it type HMOSV(guess, tolerance). The program displays the optimum and an optimum-type flag (1 for minimum, -1 for maximum, and 0 for saddle point).

The function FX in the listing implements the function to be optimized.

The listing is:

Code:
FX(x)
BEGIN
  RETURN e^(x)-3*x^2;
END;

EXPORT HMOSV(x,toler)
BEGIN
  LOCAL F0, Fp1, Fp2, Fm1, Fm2;
  LOCAL h, diff, iter, maxiters;
  LOCAL D1, D2, D3, s;
 
  maxiters:=100;
  iter := 0;
  diff := 2*toler;
  WHILE abs(diff) > toler AND iter<maxiters DO
    iter:=iter+1;
    h:=0.001*(1+ABS(x));
    F0:=FX(x);
    Fp1:=FX(x+h);
    Fp2:=FX(x+2*h);
    Fm1:=FX(x-h);
    Fm2:=FX(x-2*h);
    D1:=(Fp1-Fm1)/2/h;
    D2:=(Fp1-2*F0+Fm1)/h^2;
    D3:=(Fp2-2*Fp1+2*Fm1-Fm2)/2/h^3;
    diff:=2*D1*D2/(2*D2^2-D1*D3);
    x:=x-diff;
  END;
  IF D2 > 0.001 THEN
    s:=1; // found a minimum
  ELSE
    IF D2 < 0.001 THEN
      s:=-1; // found a maximum
    ELSE
      s:=0; // found a saddle point
    END;
  END;
  RETURN [x,s];
END;