【公式求解】线性规划(4)

例:求解线性规划问题
$ min \quad z = -4x_{1}-5x_{2} $
$ s.t. \begin{cases}
2x_{1}+x_{2} \leq 3 \\
x_{1}+2x_{2} \leq 3 \\
x_{1} \geq 0, x_{2} \geq 0
\end{cases}
$
先化为标准形
$ min \quad z = -4x_{1}-5x_{2} $
$ s.t. \begin{cases}
2x_{1}+x_{2} \leq 3 \\
x_{1}+2x_{2} \leq 3 \\
-x_{1} \leq 0, -x_{2} \leq 0
\end{cases}
$
注意:
(1)程序中虽没有直接使用NumPy库中的函数,也必须加载,否则出错
(2)数据必须写成浮点型数据,否则出错

1
2
3
4
5
6
7
8
9
10
11
import numpy as numpy
from cvxopt import matrix, solvers

c = matrix([-4.,5]) # 目标向量
A = matrix([[2.,1],[1,2],[-1,0],[0,-1]]).T
b = matrix([3.,3,0,0])

res = solvers.lp(c,A,b)

print('最优解为:', res['x'])
print('最优值为:', res['primal objective'])

例:求解线性规划
$ max \quad z = -2x_{1}-x_{2} $
$ s.t. \begin{cases}
-x_{1}+x_{2} \leq 1 \\
x_{1}+x_{2} \geq 2 \\
x_{1}-2x_{2} \leq 4 \\
x_{1}+2x_{2} = 3.5 \\
x_{2} \geq 0
\end{cases}
$
先化为标准形
$ min \quad z = 2x_{1}+x_{2} $
$ s.t. \begin{cases}
-x_{1}+x_{2} \leq 1 \\
-x_{1}-x_{2} \leq -2 \\
x_{1}-2x_{2} \leq 4 \\
x_{1}+2x_{2} = 3.5 \\
-x_{2} \leq 0
\end{cases}
$

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import numpy as numpy
from cvxopt import matrix, solvers

c = matrix([2.,1]) # 目标向量
A = matrix([[-1.,1],[-1,-1],[1,-2],[0,-1]]).T
b = matrix([1.,-2,4,0])

Aeq = matrix([1.,2],(1,2))
beq = matrix(3.5)

res = solvers.lp(c,A,b,Aeq,beq)

print('最优解为:', res['x'])
print('最优值为:', res['primal objective'])
0%