我正在使用Python设置新的线性优化代码。不幸的是,对于Pulp,Scipy和Gekko软件包,我没有相同的结果。
我试图用Python的线性优化用不同的软件包实现代码。
import numpy as np
from scipy.optimize import minimize
def objective(m):
x = m[0]
y = m[1]
z = m[2]
return 1.2*x + y + z
def constraint1(m):
return m[0] + m[1] + m[2] - 100
def constraint2(x):
return x[2]
x0 = [0,0,0]
b1 = (0,400000)
b2 = (0,200)
b3= (0,None)
bnds = (b1,b2,b3)
con1 = {'type' : 'eq', 'fun' : constraint1}
con2 = {'type' : 'ineq', 'fun' : constraint2}
cons = [con1,con2]
sol = minimize(objective,x0,method='SLSQP', bounds=bnds , constraints=cons)
print("Solution with The SCIPY package")
print(sol)
from pulp import *
prob = LpProblem("Problem",LpMinimize)
x = LpVariable("X",0,400000,LpContinuous)
y = LpVariable("Y",0,200,LpContinuous)
z = LpVariable("Z",0,None,LpContinuous)
prob += 1.2*x + y + z
prob += (x + y + z == 100)
prob.solve()
print("Solution with The PULP package")
print("Status:", LpStatus[prob.status])
for v in prob.variables():
print(v.name, "=", v.varValue)
[0.0] [36.210291349] [63.789708661]
我希望得到相同的结果,但不幸的是实际输出有所不同:
fun: 100.0000000000001
jac: array([1.19999981, 1. , 1. ])
message: 'Optimization terminated successfully.'
nfev: 35
nit: 7
njev: 7
status: 0
success: True
x: array([4.88498131e-13, 5.00000000e+01, 5.00000000e+01])
X = 0.0
Y = 100.0
Z = 0.0
{{1}}
答案 0 :(得分:3)
所有结果都是正确的/每个求解器都是正确的!
100
。sum(x) = 100
忽略浮点数限制,可以无限解决您的问题。
不同的求解器,包括不同的求解方法,可能导致不同的解决方案(请选择许多解决方案之一)。例如: