Simple If condition with a decision variable
回答済みHi, I am new with Gurobi and have a question about using if clause in my Python program. My variable can only be Q = 0 or Q > 0 and its upper bound is defined 1000. A separat function should give a 0 back If Q==0. I saw this post https://support.gurobi.com/hc/en-us/articles/4414392016529-How-do-I-model-conditional-statements-in-Gurobi- but don't get it for this simple way. Thank you for answers.
-
正式なコメント
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 Jack,
You can then add a binary variable \(b\) and define constraints \(Q \leq Q^u\cdot b\), \( Q^l\cdot b \leq Q\), where
\(b \in \{0,1\}, Q \in [0, Q^u]\) and \(0 < Q^l \leq Q^u\) is a positive lower bound on \(Q>0\). Then if \(Q = 0\), then \(b= 0\) and if \(Q \in [Q^l, Q^u]\) then \(b=1\).
Best regards,
Jaromił0 -
Hi Jaromil,
thank you very much for your advice. In Python code it should look like this, right?
UB = 1000
LB = 0
Q = model.addVar(lb=LB , ub=UB , vtype=GRB.CONTINUOUS, name="Q")
bQ = model.addVar(vtype=GRB.BINARY, name="bQ")
iQ = model.addVar(vtype=GRB.CONTINUOUS, name="iQ")
model.addConstr(Q >= LB * bQ)
model.addConstr(Q <= UB * bQ)
model.addConstr((bQ == 1) >> (iQ == 1))
model.addConstr((bQ == 0) >> (iQ == 0))0 -
Hi Jack,
This will not work with \(\texttt{LB=0}\). You have to define a small threshold because Gurobi does not accept strict inequality constraints. You could go with
UB = 1000
LB = 1e-4 # shouldn't be too small. Anything >= 1e-5 should be OK
Q = model.addVar(lb=0 , ub=UB , vtype=GRB.CONTINUOUS, name="Q")
bQ = model.addVar(vtype=GRB.BINARY, name="bQ")
model.addConstr(Q >= LB * bQ)
model.addConstr(Q <= UB * bQ)Note that you don't need the \(\texttt{iQ}\) variable, because it holds that
\[\begin{align*}
b = 0 &\rightarrow LB \cdot 0 \leq Q \leq UB \cdot 0 \\
b = 1 &\rightarrow LB \cdot 1 \leq Q \leq UB \cdot 1
\end{align*}\]Best regards,
Jaromił0
投稿コメントは受け付けていません。
コメント
4件のコメント