Skip to content

Instantly share code, notes, and snippets.

@mikezink
Created November 18, 2021 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikezink/5e5eec477292e5c06661f7b7415782b5 to your computer and use it in GitHub Desktop.
Save mikezink/5e5eec477292e5c06661f7b7415782b5 to your computer and use it in GitHub Desktop.
Linopt1.py
# Linear optimization example for the following
# optimization problem
#
# maximize: z = x + 2y
# subject to: 2x + y <= 20
# -4x + 5y <= 10
# -x + 2y >= -2
# -x + 5y = 15
# x, y >= 0
#
# Modify problem to:
# minimize: -z = -x - 2y
# subject to: 2x + y <= 20 (1)
# -4x + 5y <= 10 (2)
# x - 2y <= 2 (3)
# -x + 5y = 15 (4)
# x, y >= 0 (5)
from scipy.optimize import linprog
obj = [-1, -2]
# ─┬ ─┬
# │ └┤ Coefficient for y
# └────┤ Coefficient for x
lhs_ineq = [[2, 1], # constraint (1), left
[-4, 5], # constraint (2), left
[1, -2]] # constraint (2), left
rhs_ineq = [20, # constraint (1), right
10, # constraint (2), right
2] # constraint (3), right
lhs_eq = [[-1, 5]] # constraint (4), left
rhs_eq = [15] # constraint (4), right
bnd = [(0, float("inf")), # Bounds of x
(0, float("inf"))] # Bounds of y
opt = linprog(c=obj, A_ub=lhs_ineq, b_ub=rhs_ineq,
A_eq=lhs_eq, b_eq=rhs_eq, bounds=bnd,
method="simplex")
print(opt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment