(35S) Extremum search - Function minimization - Printable Version +- HP Forums (https://www.hpmuseum.org/forum) +-- Forum: HP Software Libraries (/forum-10.html) +--- Forum: General Software Library (/forum-13.html) +--- Thread: (35S) Extremum search - Function minimization (/thread-8308.html) |
(35S) Extremum search - Function minimization - stephane - 05-06-2017 03:01 PM We often need to optimize a function. Unfortunately, the equation solver of the HP 35s calculator is not able to find an extremum of a function. If you can't calculate the derivative of the function, or don't want to calculate it, you can then run the program below, based on the Golden section search algorithm. The program computes the minimum of a function on a given interval of values [a, b]. The function must be unimodal on this interval, otherwise the algorithm could only find a local minimum, not the global one. The function to optimize must be stored in the program Y. It must take the x value on the stack (REGX), and it must return the result into the stack too (REGX). The entire stack can be used by the program Y to compute the result of the function. Example: y=(x-2)²+3 A program for this function can be: Code:
or Code:
The minimization program that follows uses the variables A..F of the calculator, so, don't use them in the equation Y. The other variables are preserved, and are then available. Usage to minimize a function f(x) stored in Y: Stack before: Y: x_min X: x_max Run the program: XEQ E (E means Extremum, and it is on the Rdown key with the down arrow showing that we are looking for a minimum) The program then ask the user for a search tolerance value E: E? 0.0001 You can change the value if your want, but a lower value will take a longer time of computation. Press then R/S to begin the minimum search. Stack after: Y: x_min' X: x_max' x_max' - x_min' is <= given tolerance E. As x_min' and x_max' are new x bounds for the minimum value of the function, you can run again the program with a smaller value of tolerance E, or you can compute the corresponding value of the function simply keying XEQ Y now. Code of the program: Code:
Note: 0.618 comes from the Golden number, and equals 2/(1+sqrt(5)) |