我最近申请了一份工作,被要求在以下约束条件下最大化f(x,y)= x * y
:1. x一m一n一x; 2. x ~ 1m ~ 2n ~ 1x;和3.x + 2y >= 500
。当时我给出了错误的答案,但我猜得不错。用铅笔和纸加上拉格朗日乘数,我得到了x=333.4和y =166.7。然后我试着用scipy。Scipy没有最大化函数,只有最小化函数。所以,我把代价函数改为f(x,y)= -x * y并尝试最小化。我没有得到正确的答案,我得到x=250。我做错了什么?下面是代码:
from scipy.optimize import minimize
# MAX(a*b) : a+2b <= 500, a>0, b>0
# let x = [a, b]
# ref https://kitchingroup.cheme.cmu.edu/f19-06623/13-constrained-optimization.html
def objective(x):
a, b = x
return -a * b
def c1(x):
a, b = x
return -(a + 2 * b - 500)
def c2(x):
# Positivity constraint
return x[0]
def c3(x):
# Positivity constraint
return x[1]
a = 0.1
x0 = (a, 0.5 * (500 - a))
cons = [{'type': 'ineq', 'fun': f} for f in (c1, c2, c3)]
sol = minimize(objective, x0, constraints=cons)
print(sol)
a, b = sol['x']
print(f"{a * b} is a * b from the solution.")
print(f"Is a + 2b = {a + 2 * b} <= 500")
a_check = 500 - 2 * b
print(f"{a_check} is a calculated from solution value for b and should be {a}.")
1条答案
按热度按时间qlckcl4x1#
是的,它是正确的。谢谢。我用铅笔和纸拉格朗日法的解时遇到了一个问题。结果是我错了。谢谢。
M的。