Gurobi,如何将连续变量更改为二进制变量 [英] Gurobi, How to change a continuous variable to a binary variable

查看:1187
本文介绍了Gurobi,如何将连续变量更改为二进制变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用gurobi-python界面.无论如何,有没有将连续变量转换为二进制变量.我只是不想转换

I am using gurobi-python interface. Is there anyway to convert a continuous variable to a binary variable. I just do not want to convert

m.addVar(lb=0, ub=1, vtype=GRB.CONTINUOUS)

m.addVar(lb=0, ub=1, vtype=GRB.BINARY). 

我必须用另一种方式来做到这一点,而不是使用

I have to do it in another way, not using

m.addVar() 

感谢您的反馈意见.

谢谢.

推荐答案

在gurobi python API中,您可以简单地在变量上设置vtype属性.如果您保存对变量的引用,那么创建变量就很容易

In the gurobi python API, you can simply set the vtype attribute on the variable. It is easy if you save a reference to the variable In your case, if you create a varaible

x = m.addVar(lb=0, ub=1, vtype=GRB.CONTINUOUS)

您可以设置其属性

x.vtype = GRB.BINARY

在较长的示例中,您可以看到它的工作.

You can see it work in this longer example.

import gurobipy  as grb
GRB = grb.GRB
m = grb.Model()

x = m.addVar(0.0, 1.0, vtype=GRB.CONTINUOUS)
y = m.addVar(0.0, 1.0, vtype=GRB.CONTINUOUS)
m.update()
# add constraints so that y >= |x - 0.75|
m.addConstr(y >= x-0.75)
m.addConstr(y >= 0.75 - x)
m.setObjective(y)
m.update()
m.optimize()
print x.X
# 0.75
x.vtype=GRB.BINARY
m.optimize()
print x.X
# 1.0

在第一个求解中,x是连续的,因此x的最佳值为0.75.在第二个求解中,x为二进制,因此x的最佳值为1.0.

In the first solve, x was continuous, so the optimal value for x was 0.75. In the second solve, x was binary, so the optimal value for x was 1.0.

这篇关于Gurobi,如何将连续变量更改为二进制变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆