在Python中找到多变量功能的最小值和最大值

发布于 2025-01-25 07:54:23 字数 144 浏览 2 评论 0原文

我有一个功能,我想找到其最大值和最小值。我的功能是:

fuc = x * (4 - x * y)

我有一个x [-1,1]和y [2,10]的间隔。我想找到一种限制在此间隔的方法,以发现此功能的最大值和最小值。

I have a function and I would like to find its maximum and minimum values. My function is this:

fuc = x * (4 - x * y)

I have an interval for x [-1, 1] and y [2, 10]. I would like to find a way, limited to this interval, to discover the max and min values of this function.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

╭ゆ眷念 2025-02-01 07:54:23

使用 >

from scipy.optimize import minimize
import numpy as np

func = lambda x: x[0] * (4 - x[0] * x[1])
x0 = np.array([0, 2])
bounds = [(-1, 1), (2, 10)]
min_val = minimize(func, x0, bounds=bounds).fun
max_val = minimize(lambda x: -func(x), x0, bounds=bounds).fun

print(min_val, max_val)

输出:

-14.0 -2.0

感谢@Joni指出参数bunds应使用而不是简单的约束。

Use scipy.optimize.minimize:

from scipy.optimize import minimize
import numpy as np

func = lambda x: x[0] * (4 - x[0] * x[1])
x0 = np.array([0, 2])
bounds = [(-1, 1), (2, 10)]
min_val = minimize(func, x0, bounds=bounds).fun
max_val = minimize(lambda x: -func(x), x0, bounds=bounds).fun

print(min_val, max_val)

Output:

-14.0 -2.0

Thank @joni for pointing out that the parameter bounds should be used instead of simple constraints.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文