Printing the values of variables at optimal solution
回答済みDear Gurobi Team,
I have a operation research' optimization model with certain parameters (fixed values) and some decision variables (variable values that needs to be find out) in my gurobi model my constraints were in style of for loop iterations such as:
and i found the optimal solution but while printing the decision variable values i am using this code:
if model.status == GRB.OPTIMAL:
print("Optimal solution found!")
# Print objective value
print("Objective value:", model.objVal)
# Print decision variable values
for v in model.getVars():
print(v.varName, "=", v.x)
else:
print("Optimal solution not found.")
But it prints all the possible values of all decision variables (that are too much, as attached in photo) but i need only those corresponding values decision variables at which the optimal solution happen.
Please help me out as soon as possible
Thanks in advance
-
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,
Mario0 -
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 method0 -
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
サインインしてコメントを残してください。
コメント
3件のコメント