gurobi python demo
时间: 2023-08-13 17:12:00 浏览: 85
gurobi python资源
Sure! Here's a simple Python demo using Gurobi, a popular optimization solver:
```python
import gurobipy as gp
from gurobipy import GRB
# Create a new model
model = gp.Model("demo")
# Create variables
x = model.addVar(vtype=GRB.CONTINUOUS, name="x")
y = model.addVar(vtype=GRB.CONTINUOUS, name="y")
# Set objective function
model.setObjective(2*x + 3*y, GRB.MAXIMIZE)
# Add constraints
model.addConstr(x + y <= 5, name="c1")
model.addConstr(4*x - y >= 1, name="c2")
# Optimize the model
model.optimize()
# Print the solution
if model.status == GRB.OPTIMAL:
print("Optimal solution found!")
print(f"x = {x.x}")
print(f"y = {y.x}")
else:
print("No solution found.")
```
This demo creates a simple optimization model with two variables `x` and `y`. It sets the objective function as `2*x + 3*y` and adds two constraints. The model is then optimized using the `optimize()` method. Finally, it prints the optimal solution if one is found.
阅读全文