2

I'm trying to solve the simple example found in https://en.wikipedia.org/wiki/Integer_programming#Example using the CVXOPT library on Python 2.7 ; The optimal answers are either (1,2) or (2,2). I'm getting (0.0 , 0.0). What am I doing wrong in the code below ? Thanks !

import numpy as np
import cvxopt
from cvxopt import glpk

c=cvxopt.matrix([0,-1]) #-1 since we're maximising the 2nd variable
G=cvxopt.matrix([[-1,1],[3,2],[2,3],[-1,0],[0,-1]],tc='d')
h=cvxopt.matrix([1,12,12,0,0],tc='d')
(status, x)=glpk.ilp(c,G.T,h,B=set([0,1]))
print status
print x[0],x[1]    #should be (1,2) or (2,2)
print sum(c.T*x)
4

2 回答 2

6

您的代码基本上是正确的,但需要进行两个小修改:

  1. c 向量也必须是双精度的。
  2. 变量 x[0] 和 x[1] 应该是整数,而不是二进制。

然后,一个可行的解决方案由下式给出:

import numpy as np
import cvxopt

c=cvxopt.matrix([0,-1],tc='d')
G=cvxopt.matrix([[-1,1],[3,2],[2,3],[-1,0],[0,-1]],tc='d')
h=cvxopt.matrix([1,12,12,0,0],tc='d')
(status, x)=cvxopt.glpk.ilp(c,G.T,h,I=set([0,1]))
print status
print x[0],x[1] 
print sum(c.T*x)
于 2016-08-13T13:48:09.790 回答
0

Python 3.8.8 更新

from cvxopt.glpk import ilp
import numpy as np
from cvxopt import matrix
c=matrix([0,-1],tc='d')
G=matrix([[-1,1],[3,2],[2,3],[-1,0],[0,-1]],tc='d')
h=matrix([1,12,12,0,0],tc='d')
(status, x)=ilp(c,G.T,h,I=set([0,1]))
print (status)
print (x[0],x[1])
print (sum(c.T*x))

来电:

cvxopt.glpk.ilp(c,G.T,h,I=set([0,1]))

返回:模块 'cvxopt' 没有属性 'glpk'

于 2021-12-06T08:46:11.807 回答