How to write if-else in the form of constraints?

1.4k Views Asked by At

I want to write the following if-else in the form of linear or mixed integer constraints:

If $Y=k$ then $\phi=\beta$ else $\phi=0$

$Y$ and $\phi$ are variables.

$Y, \phi \geq 0$

$k, \beta >0$

$Y, \phi, k, \beta$ are all integer.

2

There are 2 best solutions below

2
On

I think you need three new binary decision variables:

  • $x_1$ will equal 1 if $Y \ge k$ and 0 otherwise
  • $x_2$ will equal 1 if $k \ge Y$ and 0 otherwise
  • $x_3$ will equal 1 if $Y = k$ and 0 otherwise.

Let $M$ be a large constant.

Add the following constraints: $$\begin{alignat}{2} Mx_1 & \ge Y - k + 1 && \qquad (1) \\ M(1-x_1) & \ge k - Y && \qquad (2) \\ Mx_2 & \ge k - Y + 1 && \qquad (3) \\ M(1-x_2) & \ge Y - k. && \qquad (4) \end{alignat}$$

The logic is:

  • If $Y > k$, then constraint (1) says that $x_1$ must equal 1, constraint (4) says that $x_2$ must equal 0, and the other two constraints have no effect.
  • If $k > Y$, then constraint (2) says that $x_1$ must equal 0, constraint (3) says that $x_2$ must equal 1, and the other two constraints have no effect.
  • If $Y = k$, then constraint (1) says that $x_1$ must equal 1, constraint (3) says that $x_2$ must equal 1, and the other two constraints have no effect.

Note that this logic relies on the fact that all of the parameters and variables are integers.

Now add: $$\begin{alignat}{2} x_3 & \ge x_1 + x_2 - 1 &\qquad& (5) \\ x_3 & \le x_1 && (6) \\ x_3 & \le x_2 && (7) \end{alignat}$$

Constraints (5)-(7) say that $x_3 = 1$ iff $x_1 = x_2 = 1$.

Finally, add the following constraint: $$\phi = \beta x_3.$$ That is, if $x_3 = 1$ then $\phi=\beta$ and if $x_3 = 0$ then $\phi=0$.

I feel like there's probably a simpler way to do this...maybe someone else will have some ideas.

0
On

Suppose $Y$ has upper bound $U$. Introduce binary variables $z_1, z_2, z_3$ and linear constraints: \begin{equation} z_1+z_2+z_3 =1\\ 0z_1+k z_2+(k+1)z_3 \le Y \le (k-1)z_1+k z_2+Uz_3\\ \phi = \beta z_2 \end{equation} To check the correctness, note the three possibilities for $z=(z_1,z_2,z_3)$:

  • If $z=(1,0,0)$ then $0 \le Y \le k-1$ and $\phi=0$.
  • If $z=(0,1,0)$ then $k \le Y \le k$, hence $Y = k$, and $\phi=\beta$.
  • If $z=(0,0,1)$ then $k+1 \le Y \le U$ and $\phi=0$.