我最近申请了一份工作,并被要求在约束条件下最大化f(x,y)= x * y
:1。x > 0
;2.y > 0
;和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}.")
是的,没错。非常感谢。我的纸笔拉格朗日法解有个问题。原来我错了。非常感谢。
M。