Consider two binary variables $p_1$ and $p_2$. Suppose, $x$ is a continuous variable that should not take values between $a$ and $b$.

Here is my try:

$$ p_1 =1 \mbox{ if } x \le a \\ p_1 =0 \mbox{ if } x >a \\ p_2 =1 \mbox{ if } x \ge b \\ p_2 =0 \mbox{ if } x < b $$ Now what will be the final equations?? $$ p_1+p_2=1 $$


2 Answers 2


You want to model $$ x \le a \mbox{ or } x \ge b $$ which you can enforce with a binary variable $p\in \{0,1\}$ and big M constraints: \begin{align} b - M_1p \le x&\le a +M_2(1-p) \\ \end{align}

The LHS enforces $p=0 \implies x\ge b$, while the RHS enforces $p=1 \implies x \le a$:

  • if $p=0$, the constraint becomes $$ b \le x\le a +M_2 $$
  • if $p=1$, the constraint becomes $$ b - M_1 \le x \le a $$

If $x \ge 0$, you could set $M_1$ to $b$. $M_2$ is either an upper bound on $x-a$ (if available), or a large constant.

  • $\begingroup$ I gave you a +1, but it might be good to explicitly specify the $M$ values, especially because the best choices for $M$ are different values in the two places. $\endgroup$
    – RobPratt
    Commented Jun 6, 2023 at 20:47
  • $\begingroup$ Agreed! I have specified the $M$ values for the answer to be more thorough. $\endgroup$
    – Kuifje
    Commented Jun 6, 2023 at 20:51
  • $\begingroup$ Can you please share more explanation on M1 and M2 $\endgroup$
    – user11940
    Commented Jun 7, 2023 at 3:26
  • $\begingroup$ @user11940 $M_1$ and $M_2$ are "large" constants, which should be as small as possible for numerical issues (see for example this link). $\endgroup$
    – Kuifje
    Commented Jun 7, 2023 at 6:31

Assuming $ b \lt a$ you can try

$ x + \epsilon \le b + Mp$
if $ p=0$ then $ x \lt b$, the 2nd constr becomes meaningless.

$ a+\epsilon \le x + M(1-p)$
if $p=1$ $x \gt a$, 1st constr turns meaningless & since $ b \lt a$ so $x$ cant be $[b,a]$

$M$ is a reasonably big number, maybe upper bound of $x$ and $\epsilon$ is a very small number to take care $\lt$.

  • $\begingroup$ your $p$ is my $1-p$ $\endgroup$
    – Kuifje
    Commented Jun 6, 2023 at 20:37
  • $\begingroup$ And your $(b,a)$ is @Kuifje's $(a,b)$. $\endgroup$
    – RobPratt
    Commented Jun 6, 2023 at 20:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.