Skip to main content

Printing the values of variables at optimal solution

Answered

Comments

3 comments

  • Mario Ruthmair
    Gurobi Staff Gurobi Staff

    Hi Muhammad,

    This is coming from our Gurobi AI Guide:

    To filter and print only the non-zero decision variable values in your Gurobi optimization model, you can modify your existing code snippet to check if the value of each variable (v.x) is non-zero before printing. This will help in focusing on those variables that actually contribute to the solution.

    Here's how you can modify your code:

    if model.status == GRB.OPTIMAL:
        print("Optimal solution found!")

        # Print objective value
        print("Objective value:", model.objVal)

        # Print decision variable values that are non-zero
        for v in model.getVars():
            if v.x != 0:
                print(v.varName, "=", v.x)

    else:
        print("Optimal solution not found.")

    This modification adds a simple condition if v.x != 0 to check the value of each variable before printing. It ensures that only those variables with a significant (non-zero) value are displayed, reducing the clutter in your output and highlighting the active variables at the optimal solution.

    Note that all the variables in your screenshot contribute to the found optimal solution since they have a non-zero solution value.

    Best regards,
    Mario

    0
  • Muhammad Ahmad Iqbal
    First Comment
    First Question

    hi,

    it still generating all the possible values but not the corresponding specific variable values of specific indices that corresponds to that optimal solution

    Please give me some other method

    0
  • Mario Ruthmair
    Gurobi Staff Gurobi Staff

    The found optimal solution is defined by the solution values of all variables in the model. If variables have a non-zero value, then they are part of the optimal solution. If you think too many variables are non-zero and should not be part of a solution, your model formulation is potentially wrong.
    For example, if only one of your "Egtineg" variables with first index 1 is allowed to be non-zero, then you have to formulate this requirement with constraints.

    0

Please sign in to leave a comment.