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 zero matrix using Python and Numpy?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How can I check if a certain version of Python is compatible with SciPy?
- How do I use the NumPy transpose function in Python?
- How do I use the scipy ttest_ind function in Python?
- How do I convert a Python numpy.ndarray to a list?
- How do I use Python and SciPy to create a tutorial PDF?
- How to use Python, XML-RPC, and NumPy together?
See more codes...