I have a function and I would like to find its maximum and minimum values. My function is this:
def function(x, y):
exp = (math.pow(x, 2) + math.pow(y, 2)) * -1
return math.exp(exp) * math.cos(x * y) * math.sin(x * y)
I have an interval for x [-1, 1] and y [-1, 1]. I would like to find a way, limited to this interval, to discover the max and min values of this function.
Here, the maximum value f(x) at x = 1 is called the absolute maximum value, global maximum or greatest value of the function f on the closed interval [0, 1]. Similarly, the minimum value of f(x) at x = 0 is called the absolute minimum value, global minimum or least value of the function f on the closed interval [0, 1].
You can find this minimum value by graphing the function or by using one of the two equations. If you have the equation in the form of y = ax^2 + bx + c, then you can find the minimum value using the equation min = c - b^2/4a.
If you are given the formula y = ax2 + bx + c, then you can find the maximum value using the formula max = c - (b2 / 4a). If you have the equation y = a(x-h)2 + k and the a term is negative, then the maximum value is k.
Using, for instance, scipy
's fmin
(which contains an implementation of the Nelder-Mead algorithm), you can try this:
import numpy as np
from scipy.optimize import fmin
import math
def f(x):
exp = (math.pow(x[0], 2) + math.pow(x[1], 2)) * -1
return math.exp(exp) * math.cos(x[0] * x[1]) * math.sin(x[0] * x[1])
fmin(f,np.array([0,0]))
which yields the following output:
Optimization terminated successfully.
Current function value: -0.161198
Iterations: 60
Function evaluations: 113
array([ 0.62665701, -0.62663095])
Please keep in mind that:
1) with scipy
you need to convert your function into a function accepting an array (I showed how to do it in the example above);
2) fmin
uses, like most of its pairs, an iterative algorithm, therefore you must provide a starting point (in my example, I provided (0,0)
). You can provide different starting points to obtain different minima/maxima.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With