from cvxopt import solvers, matrix
P = matrix([[1.0,0.0],[0.0,0.0]]) # matrix里区分int和double,所以数字后面都需要加小数点
q = matrix([3.0,4.0])
G = matrix([[-1.0,0.0,-1.0,2.0,3.0],[0.0,-1.0,-3.0,5.0,4.0]])
h = matrix([0.0,0.0,-15.0,100.0,80.0])
sol = solvers.qp(P,q,G,h) # 调用优化函数solvers.qp求解
print(sol['x']) # 打印结果,sol里面还有很多其他属性,读者可以自行了解
5.运行及其结果
$ python3 example.py
pcost dcost gap pres dres
0: 1.0780e+02 -7.6366e+02 9e+02 1e-16 4e+01
1: 9.3245e+01 9.7637e+00 8e+01 1e-16 3e+00
2: 6.7311e+01 3.2553e+01 3e+01 6e-17 1e+00
3: 2.6071e+01 1.5068e+01 1e+01 2e-16 7e-01
4: 3.7092e+01 2.3152e+01 1e+01 2e-16 4e-01
5: 2.5352e+01 1.8652e+01 7e+00 8e-17 3e-16
6: 2.0062e+01 1.9974e+01 9e-02 6e-17 3e-16
7: 2.0001e+01 2.0000e+01 9e-04 6e-17 3e-16
8: 2.0000e+01 2.0000e+01 9e-06 9e-17 2e-16
Optimal solution found.
[ 7.13e-07]
[ 5.00e+00]