Python 查找函数的最小值和最大值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18965195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find minimum and maximum values of a function
提问by pceccon
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.
我有 x [-1, 1] 和 y [-1, 1] 的间隔。我想找到一种方法,仅限于这个区间,来发现这个函数的最大值和最小值。
采纳答案by Emanuele Bezzi
Using, for instance, scipy
's fmin
(which contains an implementation of the Nelder-Mead algorithm), you can try this:
例如,使用scipy
's fmin
(其中包含 Nelder-Mead 算法的实现),您可以尝试以下操作:
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);
1)scipy
您需要将函数转换为接受数组的函数(我在上面的示例中展示了如何执行此操作);
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.
2)fmin
像大多数对一样,使用迭代算法,因此您必须提供一个起点(在我的示例中,我提供了(0,0)
)。您可以提供不同的起点以获得不同的最小值/最大值。
回答by Shashank
Here is something which gives fairly close estimates (not exact).
这是给出了相当接近的估计(不准确)的东西。
import math
import random
import sys
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)
max_func = - sys.maxint - 1
min_func = sys.maxint
maximal_x, maximal_y = None, None
minimal_x, minimal_y = None, None
for i in xrange(1000000):
randx = random.random()*2 - 1
randy = random.random()*2 - 1
result = function(randx, randy)
max_func = max(max_func, result)
if max_func == result:
maximal_x, maximal_y = randx, randy
min_func = min(min_func, result)
if min_func == result:
minimal_x, minimal_y = randx, randy
print "Maximal (x, y):", (maximal_x, maximal_y)
print "Max func value:", max_func, '\n'
print "Minimal (x, y):", (minimal_x, minimal_y)
print "Min func value:", min_func