Maximize Optimization using Scipy
python, scipy
Solution
Your code has the following issues:
- The way you are passing your `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 `<=`.
- The upper bound in `b2` does not correspond to the bound implied by the constraint `2*x2 <= 12`.
Problem
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) ```