Skip to main content

something problems in Python code

Answered

Comments

1 comment

  • Gurobot (AI-generated response)
    Gurobi Staff Gurobi Staff

    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:

    1. When x >= 0, the objective is 2 * x.
    2. 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:

    • x is your variable that can take any real value.
    • x_pos and x_neg are auxiliary variables representing the positive and negative parts of x, respectively.
    • The constraint x == x_pos - x_neg splits x 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 with GRB.MINIMIZE if you intend to minimize the objective function instead.

    0

Please sign in to leave a comment.