I'm setting up a new linear optimization code with Python. Unfortunately, I don't have the same results with Pulp, Scipy and Gekko packages.
I tried to implement code with different packages for Linear Optimization in Python.
from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt
m = GEKKO() # create GEKKO model
x = m.Var(value=0, lb=0, ub=400000) # define new variable, initial value=0
y = m.Var(value=0, lb=0, ub=200) # define new variable, initial value=1
z = m.Var(value=0, lb=0)
m.Equation(x+y+z==100)
m.Obj(1.2*x + y + z) # equations
m.solve(disp=False) # solve
print("Solution with The GEKKO package")
print(x.value, y.value , z.value)# # print solution
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)
I expect to have the same results , but the actual outputs are Different unfortunately :
[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
All results are correct / Every solver is correct!
100
. sum(x) = 100
Ignoring floating-point limitations, there are infinitely many different optimal solutions for your problem.
Different solvers including different solving approaches can lead to different solutions (picking one of many solutions). Here for example:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.