gpt4 book ai didi

python-2.7 - Python - CVXOPT 中的整数线性规划 (ILP) 函数未生成正确的结果

转载 作者:行者123 更新时间:2023-12-05 01:46:45 24 4
gpt4 key购买 nike

我正在尝试解决在 https://en.wikipedia.org/wiki/Integer_programming#Example 中找到的简单示例在 Python 2.7 上使用 CVXOPT 库;最佳答案是 (1,2) 或 (2,2)。我得到(0.0,0.0)。我在下面的代码中做错了什么?谢谢!

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)

最佳答案

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

  1. c 向量也必须是 double 。
  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)

关于python-2.7 - Python - CVXOPT 中的整数线性规划 (ILP) 函数未生成正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33785396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com