10

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.

4

2 回答 2

17

例如,使用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]))

产生以下输出:

Optimization terminated successfully.
     Current function value: -0.161198
     Iterations: 60
     Function evaluations: 113 
array([ 0.62665701, -0.62663095])

请记住:

1)scipy您需要将您的函数转换为接受数组的函数(我在上面的示例中展示了如何做到这一点);

2)fmin像它的大多数对一样,使用迭代算法,因此您必须提供一个起点(在我的示例中,我提供了(0,0))。您可以提供不同的起点来获得不同的最小值/最大值。

于 2013-09-23T18:27:40.237 回答
0

这是给出了相当接近的估计(不准确)的东西。

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
于 2013-09-23T18:06:37.553 回答