Gurobi获得变量的值

联系我:ligong15 AT foxmail.com

 

第一种方法:

在Gurobi+python的过程中,想获得具体变量的值用来图形化,搜索了一下,找到了如下内容,但该方式速度较慢。

转自:https://stackoverflow.com/questions/16436834/gurobi-python-get-value-of-the-defined-variable

 

How do i get the value of the variable that i have define previously(using addVar) in gurobi python? I need to compare the value of the gurobi variable and then perform calculations to reach to my objective variable. The same has to be done before optimization.

 

 

You have two options. The most straightforward is to save a reference to the Var object returned by Model.addVar. Another way is to give a name your variables with the name parameter in addVar, then retrieve the variable with Model.getVarByName.

from gurobipy import *
a_var = m.addVar(name="variable.0")
# ...
a_var_reference = m.getVarByName("variable.0")
# a_var and a_var_reference refer to the same object
m.optimize()
#obtain the value of a_var in the optimal solution
if m.Status == GRB.OPTIMAL:
   print a_var.X

 

所以方法是m.getVarByName(变量名称)

 

 

第二种方法:

后来在google group中看到一个帖子:https://groups.google.com/forum/#!topic/gurobi/KqemTUUUvoQ

gurobi的专家说有两种方式:1、在创建变量时,将其存到一个集合中;2、上文中说到的根据变量名查找变量,但是速度较慢

在python中,实现方法如下:

 

yvars = mode.addVars(10,10)

xvars = model.addVars(7,10)

 

 

 

在调用的时候,直接调用,例如yvars[5,6],想查看变量的值的话,yvars[5,6].x,其余变量的性质参见gurobi文档

在这里我一开始认识有误,以为yvars是固有格式或者变量名。这样创建变量的时候直接存储,可以在后续方便的调用。

 

 

你可能感兴趣的:(数学建模)