I'm trying to solve this linear programming function with the restraints shown below, the answer for x1
and x2
should be 2
and 6
respectively, and the value of the objective function should be equal to 36
. The code that I wrote gives me as answers 4
and 3
. What may I be doing wrong? Function to maximize z=3*x1 + 5*x2
. Restraints are 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)
The SciPy Optimize library provides a set of functions to minimize (or maximize) objective functions.
NumPy/SciPy's functions are usually optimized for multithreading. Did you look at your CPU utilization to confirm that only one core is being used while the simulation is being ran? Otherwise you have nothing to gain from running multiple instances.
optimize. minimize can be terminated by using tol and maxiter (maxfev also for some optimization methods). There are also some method-specific terminators like xtol, ftol, gtol, etc., as mentioned on scipy.
Your code has the following issues:
objective
to minimize
results in a minimization rather than a maximization of the objective. If you want to maximize objective
with minimize
you should set the sign
parameter to -1
. See the maximization example in scipy documentation.minimize
assumes that the value returned by a constraint function is greater than zero. Therefore, the way you have written your constraint implies that 3*x1 + 2*x2 - 18.0 >=0
, whereas the actual constraint employs <=
. b2
does not correspond to the bound implied by the constraint 2*x2 <= 12
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With