Ostrowski's method for optimizing a single-variable function

+- 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: Ostrowski's method for optimizing a single-variable function (/thread-23383.html)



Ostrowski's method for optimizing a single-variable function - Namir - 2025-04-07

The following HP Prime program performs single-variable optimization using Ostrowski's method. To use it type OMOSV(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 OMOSV(x,toler)
BEGIN
  LOCAL F0, Dy, Fp1, Fp2, Fm1, Fm2;
  LOCAL h, diff, iter, maxiters;
  LOCAL D1, D2, s, y, lastX;
 
  maxiters:=100;
  iter := 0;
  diff := 2*toler;
  lastX:=x;
  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;
    y:=x-D1/D2;
    h:=0.001*(1+ABS(y));
    Dy:=(FX(y+h)-FX(y-h))/2/h;
    IF D1==2*Dy THEN
      BREAK;
    END;
    x:=y-Dy*(x-y)/(D1-2*Dy);
    diff:=x-lastX;
    lastX:=x;
  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;