利用Gurobi求解线性整数规划问题(Python)
作者:互联网
代码
from gurobipy import *
m = Model("Integer Linear Programming")
# 定义变量
x1 = m.addVar(lb=0, ub=150, vtype=GRB.INTEGER, name='x1')
x2 = m.addVar(lb=0, ub=150, vtype=GRB.INTEGER, name='x2')
x3 = m.addVar(lb=0, ub=150, vtype=GRB.INTEGER, name='x3')
x4 = m.addVar(lb=0, ub=150, vtype=GRB.INTEGER, name='x4')
x5 = m.addVar(lb=0, ub=150, vtype=GRB.INTEGER, name='x5')
x6 = m.addVar(lb=0, ub=150, vtype=GRB.INTEGER, name='x6')
x7 = m.addVar(lb=0, ub=150, vtype=GRB.INTEGER, name='x7')
x8 = m.addVar(lb=0, ub=150, vtype=GRB.INTEGER, name='x8')
# 添加约束
m.addConstr(2*x1 + x2 + x3 + x4 >= 100)
m.addConstr(2*x2 + x3 + 3*x5 + 2*x6 + x7 >= 150)
m.addConstr(x1 + x3 + 3*x4 + 2*x6 + 3*x7 + 5*x8 >= 100)
# 添加目标函数
m.setObjective(5*x1 + 6*x2 + 23*x3 + 5*x4 + 24*x5 + 6*x6 + 23*x7 + 5*x8, GRB.MINIMIZE)
# 求解
m.optimize()
print('*' * 60)
print('最优值:', m.objVal)
for v in m.getVars():
print('参数', v.varName, '=', v.x)
结果
C:\Users\86158\Anaconda3\python.exe "C:/Users/86158/Documents/Python Scripts/Python_optimization_algorithms_trainning-master/Python最优化算法实战/源代码/第2章-源文件/代码2-2 gurobi求解线性规划模型.py"
Using license file C:\Users\86158\gurobi.lic
Gurobi Optimizer version 9.1.1 build v9.1.1rc0 (win64)
Thread count: 4 physical cores, 8 logical processors, using up to 8 threads
Optimize a model with 3 rows, 8 columns and 15 nonzeros
Model fingerprint: 0xe8479eef
Variable types: 0 continuous, 8 integer (0 binary)
Coefficient statistics:
Matrix range [1e+00, 5e+00]
Objective range [5e+00, 2e+01]
Bounds range [2e+02, 2e+02]
RHS range [1e+02, 2e+02]
Found heuristic solution: objective 3950.0000000
Presolve time: 0.00s
Presolved: 3 rows, 8 columns, 15 nonzeros
Variable types: 0 continuous, 8 integer (0 binary)
Root relaxation: objective 6.000000e+02, 3 iterations, 0.00 seconds
Nodes | Current Node | Objective Bounds | Work
Expl Unexpl | Obj Depth IntInf | Incumbent BestBd Gap | It/Node Time
* 0 0 0 600.0000000 600.00000 0.00% - 0s
Explored 0 nodes (3 simplex iterations) in 0.00 seconds
Thread count was 8 (of 8 available processors)
Solution count 2: 600 3950
Optimal solution found (tolerance 1.00e-04)
Best objective 6.000000000000e+02, best bound 6.000000000000e+02, gap 0.0000%
************************************************************
最优值: 600.0
参数 x1 = 30.0
参数 x2 = 40.0
参数 x3 = -0.0
参数 x4 = -0.0
参数 x5 = -0.0
参数 x6 = 35.0
参数 x7 = -0.0
参数 x8 = -0.0
Process finished with exit code 0
标签:150,vtype,lb,name,求解,Python,GRB,INTEGER,Gurobi 来源: https://blog.csdn.net/MarcoLee1997/article/details/113793885