pycharm gurobi简单程序
时间: 2023-08-29 22:12:22 浏览: 77
基于pyomo的python+gurobi实例
5星 · 资源好评率100%
以下是使用Gurobi在PyCharm中编写的简单程序示例,用于解决线性规划问题:
```python
import gurobipy as gp
# 创建模型对象
model = gp.Model()
# 创建变量
x1 = model.addVar(lb=0, ub=1, name="x1")
x2 = model.addVar(lb=0, ub=1, name="x2")
x3 = model.addVar(lb=0, ub=1, name="x3")
# 添加约束条件
model.addConstr(x1 + x2 + x3 <= 1, name="c1")
model.addConstr(2 * x1 + x2 + 3 * x3 <= 2, name="c2")
model.addConstr(x1 + 2 * x2 + x3 <= 2, name="c3")
# 设置目标函数
model.setObjective(3 * x1 + 2 * x2 + x3, gp.GRB.MAXIMIZE)
# 求解线性规划问题
model.optimize()
# 输出结果
print("Optimal solution:")
print("x1 =", x1.x)
print("x2 =", x2.x)
print("x3 =", x3.x)
print("Optimal objective value:", model.objVal)
```
此程序解决了以下线性规划问题:
```
maximize 3x1 + 2x2 + x3
subject to
x1 + x2 + x3 <= 1
2x1 + x2 + 3x3 <= 2
x1 + 2x2 + x3 <= 2
x1, x2, x3 >= 0
```
输出结果为:
```
Optimal solution:
x1 = 0.0
x2 = 1.0
x3 = 0.0
Optimal objective value: 2.0
```
阅读全文