我正在尝试使用下面显示的约束解决此线性编程函数,x1
和x2
的答案应分别为2
和6
,并且目标函数的值应等于36
。我写的代码为我提供了答案4
和3
。我可能做错了什么?最大化z=3*x1 + 5*x2
的功能。约束是x1 <= 4
; 2*x2 <=12
; 3*x1 + 2*x2 <= 18
; x1>=0
; x2>=0
import numpy as np
from scipy.optimize import minimize
def objective(x, sign=1.0):
x1 = x[0]
x2 = x[1]
return sign*((3*x1) + (5*x2))
def constraint1(x, sign=1.0):
return sign*(3*x[0] +2*x[1]- 18.0)
x0=[0,0]
b1 = (0,4)
b2 = (0,12)
bnds= (b1,b2)
con1 = {'type': 'ineq', 'fun': constraint1}
cons = [con1]
sol = minimize (objective,x0,method='SLSQP',bounds=bnds,constraints=cons)
print(sol)
答案 0 :(得分:8)
您的代码存在以下问题:
objective
传递给minimize
的方式会导致最小化而不是目标的最大化。如果您想最大化 objective
minimize
,则应将sign
参数设置为-1
。请参阅scipy documentation中的最大化示例。minimize
假设约束函数返回的值大于而不是零。因此,编写约束的方式意味着3*x1 + 2*x2 - 18.0 >=0
,而实际约束使用<=
。 b2
的上限与约束2*x2 <= 12
隐含的界限不对应。答案 1 :(得分:1)
如果有人想要工作代码,请在下面。我还添加了cvx。解决方案是x:array([2。,6。])
def objective(x, sign=-1.0):
x1 = x[0]
x2 = x[1]
return sign*(3*x1 + 5*x2)
def constraint1(x):
return 18.0 - 3*x[0] -2*x[1]
x0 = [0,0]
b1 = (0,4)
b2 = (0,6)
bnds= (b1,b2)
con1 = {'type': 'ineq', 'fun': constraint1}
cons = [con1]
sol = minimize(objective, x0, method='SLSQP', bounds = bnds, constraints = cons)
print(sol)
# Create two scalar optimization variables (CVXPY Variable)
x1 = cp.Variable()
x2 = cp.Variable()
# Create two constraints (Python list)
constraints = [3*x1 + 2*x2 <= 18, x1 >= 0, x2 >= 0, x1 <=4, x2 <= 6]
# Form objective
obj = cp.Maximize(3*x1 + 5*x2)
# Form and solve problem
prob = cp.Problem(obj, constraints)
prob.solve() # Returns the optimal value.
print("status:", prob.status)
print("optimal value", np.round(prob.value, 5))
print("optimal var", np.round(x1.value, 5), np.round(x2.value, 5))