python-scipyHow can I use Python and SciPy to solve a linear programming problem?
Python and SciPy can be used to solve linear programming problems using the scipy.optimize module. This module contains a variety of functions for minimizing and maximizing objectives with constraints. For example, the scipy.optimize.linprog function can be used to solve a linear programming problem.
For example, the following code block solves a linear programming problem with two variables and two constraints:
import scipy.optimize as opt
# Objective function
c = [1, 4]
# Constraints
A = [[3, 2], [2, 5]]
b = [15, 20]
# Bounds
x1_bounds = (0, None)
x2_bounds = (0, None)
res = opt.linprog(c, A_ub=A, b_ub=b, bounds=(x1_bounds, x2_bounds))
print(res)
The output of this code is:
fun: -14.000000000000007
message: 'Optimization terminated successfully.'
nit: 2
slack: array([0., 0.])
status: 0
success: True
x: array([2., 6.])
The parts of this code are:
import scipy.optimize as opt: imports the SciPy optimize module.c = [1, 4]: defines the objective function.A = [[3, 2], [2, 5]]: defines the constraints.b = [15, 20]: defines the constraints.x1_bounds = (0, None)andx2_bounds = (0, None): defines the bounds for the variables.res = opt.linprog(c, A_ub=A, b_ub=b, bounds=(x1_bounds, x2_bounds)): solves the linear programming problem.print(res): prints the result of the optimization.
Helpful links
More of Python Scipy
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- 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 Scipy zeros in Python?
- How can I use Python and Numpy to zip files?
- How do I use the Scipy freqz function in Python?
- How can I use Python and SciPy to find the zeros of a function?
- How do I use Python Scipy to perform a Z test?
- How do I rotate an image using Python and SciPy?
- How to use Python, XML-RPC, and NumPy together?
See more codes...