Python - Gurobi
目录
申请 Gurobi
学术许可和安装 Gurobi
申请 Gurobi
学术许可和安装可以参考
Gurobi最新安装与学术许可申请教程(2025) - 知乎
配置 Python
环境
首先打开命令行终端,用 Conda
单独创建一个环境:
1conda create --name name_env
激活环境:
1conda activate name_env
用 Conda
包管理安装 Gurobi
到 Python
库中1:
1conda install -c gurobi gurobi
安装完之后,可以用下面的例子测试 Gurobi
是否能够正常使用:
1import gurobipy as gp
2from gurobipy import GRB
3
4def test_gurobi():
5 try:
6 # 创建一个新的模型
7 model = gp.Model("test_model")
8
9 # 添加变量
10 x = model.addVar(name="x", vtype=GRB.CONTINUOUS, lb=0)
11 y = model.addVar(name="y", vtype=GRB.CONTINUOUS, lb=0)
12
13 # 更新模型以整合新变量
14 model.update()
15
16 # 设置目标函数:最大化 3x + 2y
17 model.setObjective(3 * x + 2 * y, GRB.MAXIMIZE)
18
19 # 添加约束条件
20 # x + y <= 4
21 model.addConstr(x + y <= 4, "c0")
22
23 # x <= 2
24 model.addConstr(x <= 2, "c1")
25
26 # y <= 3
27 model.addConstr(y <= 3, "c2")
28
29 # 优化模型
30 model.optimize()
31
32 # 检查优化状态
33 if model.status == GRB.OPTIMAL:
34 print(f"最优目标值: {model.ObjVal}")
35 print(f"x = {x.x}")
36 print(f"y = {y.x}")
37 else:
38 print("没有找到最优解。")
39
40 except gp.GurobiError as e:
41 print(f"Gurobi错误: {e}")
42
43 except Exception as e:
44 print(f"其他错误: {e}")
45
46if __name__ == "__main__":
47 test_gurobi()
如果能够正常使用会输出以下结果:
1Optimize a model with 3 rows, 2 columns and 4 nonzeros
2Model fingerprint: 0x5c2931af
3Coefficient statistics:
4 Matrix range [1e+00, 1e+00]
5 Objective range [2e+00, 3e+00]
6 Bounds range [0e+00, 0e+00]
7 RHS range [2e+00, 4e+00]
8Presolve removed 2 rows and 0 columns
9Presolve time: 0.00s
10Presolved: 1 rows, 2 columns, 2 nonzeros
11
12Iteration Objective Primal Inf. Dual Inf. Time
13 0 1.2000000e+01 2.000000e+00 0.000000e+00 0s
14 1 1.0000000e+01 0.000000e+00 0.000000e+00 0s
15
16Solved in 1 iterations and 0.00 seconds (0.00 work units)
17Optimal objective 1.000000000e+01
18最优目标值: 10.0
19x = 2.0
20y = 2.0