something problems in Python code
AnsweredHow can I express this problem in the language of gurobi 11 (python code), my own code always gives errors：
variable x
when x>=0，objective=2*x
whenx<0，objective=3*x
10
0

To model an optimization problem in Gurobi where the objective function changes based on the value of a variable, you can use a piecewiselinear objective function or introduce auxiliary variables and constraints to handle the different cases. For the problem you've described, you need to handle two cases based on the value of
x
: When
x >= 0
, the objective is2 * x
.  When
x < 0
, the objective is3 * abs(x)  10
.
Here's how you can express this in Gurobi using Python:
from gurobi import *
# Create a new model
m = Model("piecewiselinear")
# Create variable
x = m.addVar(lb=GRB.INFINITY, name="x")
# Auxiliary variables
x_pos = m.addVar(name="x_pos") # For positive part of x
x_neg = m.addVar(name="x_neg") # For negative part of x
# Objective function
m.setObjective(2 * x_pos  3 * x_neg  10, GRB.MAXIMIZE)
# Add constraints
m.addConstr(x == x_pos  x_neg, "x_split") # Split x into positive and negative parts
m.addConstr(x_pos >= 0, "x_pos_nonneg")
m.addConstr(x_neg >= 0, "x_neg_nonneg")
# Optimize model
m.optimize()
# Print result
if m.status == GRB.OPTIMAL:
print('Optimal value:', m.objVal)
print('x:', x.X)
else:
print('No optimal solution found.')In this code:

x
is your variable that can take any real value. 
x_pos
andx_neg
are auxiliary variables representing the positive and negative parts ofx
, respectively.  The constraint
x == x_pos  x_neg
splitsx
into its positive and negative components.  The objective function is set to maximize
2 * x_pos  3 * x_neg  10
.  Finally, the model is solved, and the optimal value of the objective function along with the value of
x
is printed.
Please replace
GRB.MAXIMIZE
withGRB.MINIMIZE
if you intend to minimize the objective function instead.0  When
Please sign in to leave a comment.
Comments
1 comment