python-scipyHow do I use Python and SciPy to solve a linear programming problem?
Linear programming is a method for finding optimal solutions to problems with multiple constraints. Python and SciPy can be used to solve linear programming problems with the scipy.optimize.linprog
function.
Example
import numpy as np
from scipy.optimize import linprog
# coefficients of the objective function
c = np.array([2, 3])
# coefficients of the constraints
A = np.array([[1, 1], [2, 3]])
# right-hand side of the constraints
b = np.array([4, 8])
# bounds on the variables
x1_bounds = (0, None)
x2_bounds = (0, None)
res = linprog(c, A_ub=A, b_ub=b, bounds=(x1_bounds, x2_bounds))
print(res)
Output example
fun: 8.0
message: 'Optimization terminated successfully.'
nit: 2
slack: array([0., 0.])
status: 0
success: True
x: array([2., 4.])
The scipy.optimize.linprog
function takes the coefficients of the objective function (c
), the coefficients of the constraints (A
), the right-hand side of the constraints (b
), and the bounds on the variables (x1_bounds
, x2_bounds
) as inputs. The output of the function is an optimization result object which contains the optimal solution (x
) and other information such as the function value (fun
) and the status of the optimization (status
).
Helpful links
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How do I create a numpy array of zeros using Python?
- How can I use Python Scipy to zoom in on an image?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How do I calculate variance using Python and SciPy?
- How to use Python, XML-RPC, and NumPy together?
- How do I use Scipy zeros in Python?
- How can I use Python and Numpy to parse XML data?
- How can I use the x.shape function in Python Numpy?
- How can I use Python Numpy to select elements from an array based on multiple conditions?
See more codes...