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
-
Official comment
This post is more than two years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum, or try Gurobot, our chatbot interface offering instant, expert-level support. -
To model an optimization problem in Gurobi where the objective function changes based on the value of a variable, you can use a piecewise-linear 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 is-3 * abs(x) - 10.
Here's how you can express this in Gurobi using Python:
from gurobi import *
# Create a new model
m = Model("piecewise-linear")
# 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:
-
xis your variable that can take any real value. -
x_posandx_negare auxiliary variables representing the positive and negative parts ofx, respectively. - The constraint
x == x_pos - x_negsplitsxinto 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
xis printed.
Please replace
GRB.MAXIMIZEwithGRB.MINIMIZEif you intend to minimize the objective function instead.0 - When
Post is closed for comments.
Comments
2 comments