查找函数的最小值和最大值 [英] Find minimum and maximum values of a function

查看:266
本文介绍了查找函数的最小值和最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,我想找到它的最大值和最小值.我的职能是这样:

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)

我有一个x [-1,1]和y [-1,1]的间隔.我想找到一种方法来限制此间隔,以发现此函数的最大值和最小值.

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.

推荐答案

例如,使用scipy

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]))

将产生以下输出:

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

请记住:

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

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像它的大多数对一样,使用迭代算法,因此您必须提供一个起点(在我的示例中,我提供了(0,0)).您可以提供不同的起点来获得不同的最小值/最大值.

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.

这篇关于查找函数的最小值和最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆