How to add such an indicator constraints? if a=b then c<d else c>d
AnsweredI would like to add this instruction constraint:
if a=b then c<d else c>d
when a=b → k =1
a !=b → k =0
I know how to handle such situations
if a<b then c<d else c>d
But I'm confused about how to handle the equation.
Kind regards,
Yu
-
Official comment
This post is more than three 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. -
Hi Yu,
For this purpose, you need several auxiliary variables. Edit: I missed one side of the implication.- A continuous variable to represent the difference \(\texttt{y} =\texttt{a}-\texttt{b}\);
- A non-negative variable to represent the absolute value of this difference: \(\texttt{yabs} = |y|\);
- And a binary variable to indicate whether \(\texttt{yabs}>=0\).
In Python, using addGenConstrIndicator (overloaded version) you can write
from gurobipy import *
m = Model()
a = m.addVar(name="a", obj=10)
b = m.addVar(name="b", obj=1)
c = m.addVar(name="c", obj=1)
d = m.addVar(name="d", obj=10)
# Some auxiliary variables
x = m.addVar(vtype=GRB.BINARY, name="x")
y = m.addVar(name="y") # difference a-b
yabs = m.addVar(lb=0, name="yabs") # absolute difference
eps = 1.0e-3
m.addConstr(y == a - b)
m.addConstr(yabs == abs_(y))
m.addConstr((x == 1) >> (yabs == 0))
m.addConstr((x == 0) >> (yabs >= eps))
m.addConstr((x == 1) >> (c <= d - eps))
m.addConstr((x == 0) >> (d <= c - eps))
m.optimize()Where the \(\texttt{eps}\) is a small number used to write strict inequalities.
Cheers,
David0 -
Hi David,
Thank you very much,it worked!
I have one more question, if a is not a decision variable(a∈[1,10]), b is a decision variable.
Can it still be solved in this way?
Best regards,
Yu
0 -
Hi Yu,
This also works! Just replace \(\texttt{a}\) with your value.
Best,
David0
Post is closed for comments.
Comments
4 comments