15

I want to express the following constraint, in an integer linear program:

$$y = \begin{cases} 0 &\text{if } x=0\\ 1 &\text{if } x\ne 0. \end{cases}$$

I already have the integer variables $x,y$ and I'm promised that $-100 \le x \le 100$. How can I express the above constraint, in a form suitable for use with an integer linear programming solver?

This will presumably require introducing some additional variables. What new variables and constraints do I need to add? Can it be done cleanly with one new variable? Two?

Equivalently, this is asking how to enforce the constraint

$$y \ne 0 \text{ if and only if } x \ne 0.$$

in the context where I already have constraints that imply $|x| \le 100$ and $0 \le y \le 1$.


(My goal is to fix an error in https://cs.stackexchange.com/a/12118/755.)

D.W.
  • 167,959
  • 22
  • 232
  • 500

3 Answers3

8

I think I can do it with one extra binary variable $\delta \in \{0,1\}$:

$$ -100y \le x \le 100 y $$ $$ 0.001y-100.001\delta \le x \le -0.001y+100.001 (1-\delta) $$

Update

This assumes $x$ is a continuous variable. If we restrict $x$ to be integer valued, then the second constraint can be simplified to: $$ y-101\delta \le x \le -y+101 (1-\delta) $$

1

The following isn't pretty by any means, but it works. Let $0 \leq x \leq N$, $N=100$ in the specific case in the question. Then we have the following constraints.

  1. $0 \leq z_1, z_2, z \leq 1$
  2. $x - N(1-z_1) \leq 0$
  3. $-x -Nz_1 \leq -1$
  4. $-x -N(1-z_2) \leq 0$
  5. $x -Nz_2 \leq -1$
  6. $z_1 + z_2 - 1 \leq z$
  7. $z \leq z_1$
  8. $z \leq z_2$

The intuition is as follows. $z_1 = 1 \iff x \leq 0$. This is encoded in constraints 2 and 3. Similarly constraints 4 and 5 encode $z_2 = 1 \iff x \geq 0$. The last three constraints express $z = z_1 \land z_2$.

Pramod
  • 111
  • 2
1

Here's a solution that uses two temporary variables. Let $t,u$ be integer zero-or-one variables, with the intended meaning that $t=1$ if $x \ge 0$, $u=1$ if $x \le 0$, and $y=\neg(t \land u)$. These can be enforced with the following constraints:

$$\begin{align*} 0 &\le t,u,y \le 1\\ 1+x &\le 101t \le 101 + x\\ 1-x &\le 101u \le 101-x\\ t+u-1 &\le 1-y\\ 1-y &\le t\\ 1-y &\le u \end{align*}$$

D.W.
  • 167,959
  • 22
  • 232
  • 500