Python-cvxopt庫的使用(1)(解決LP問題)

對於python cvxopt 庫,這個庫用於求解線性和二次規劃。本節介紹如何求解線性規劃問題。
形如以下的問題:
在這裏插入圖片描述
我們將其寫成標準形式:
min cx
s.t. Ax < b

對應寫出A,b,c矩陣。

A = matrix([ [-1.0, -1.0, 0.0, 1.0], [1.0, -1.0, -1.0, -2.0] ])
b = matrix([ 1.0, -2.0, 0.0, 4.0 ])
c = matrix([ 2.0, 1.0 ])

要注意,這裏的matrix是cvx庫的matrix寫法,要求是按列從左到右書寫。

接下來調用標準的求解器solver.lp計算:

solvers.options['show_progress'] = True
sol=solvers.lp(c,A,b)
print(sol)
print(sol['x'])

結果如下:

pcost       dcost       gap    pres   dres   k/t
 0:  2.6471e+00 -7.0588e-01  2e+01  8e-01  2e+00  1e+00
 1:  3.0726e+00  2.8437e+00  1e+00  1e-01  2e-01  3e-01
 2:  2.4891e+00  2.4808e+00  1e-01  1e-02  2e-02  5e-02
 3:  2.4999e+00  2.4998e+00  1e-03  1e-04  2e-04  5e-04
 4:  2.5000e+00  2.5000e+00  1e-05  1e-06  2e-06  5e-06
 5:  2.5000e+00  2.5000e+00  1e-07  1e-08  2e-08  5e-08
Optimal solution found.
{'x': <2x1 matrix, tc='d'>, 'y': <0x1 matrix, tc='d'>, 's': <4x1 matrix, tc='d'>, 'z': <4x1 matrix, tc='d'>, 'status': 'optimal', 'gap': 1.3974945737537904e-07, 'relative gap': 5.589978335863919e-08, 'primal objective': 2.499999989554308, 'dual objective': 2.4999999817312544, 'primal infeasibility': 1.1368786496881938e-08, 'dual infeasibility': 2.2578790069187308e-08, 'primal slack': 2.0388399547194678e-08, 'dual slack': 3.529915972560751e-09, 'residual as primal infeasibility certificate': None, 'residual as dual infeasibility certificate': None, 'iterations': 5}
[ 5.00e-01]
[ 1.50e+00]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章