# Mixed linear programming if…then

I need to model the following statement:

if $$\sum\limits_{i=1}^N X_i=k$$ then $$Y=1$$ else $$Y=0$$

$$X_i$$'s are binary variables

$$k$$ is an integer between $$0$$ and $$N$$

$$Y$$ is a binary variable

Thank you in advance.

In case $$N$$ is a constant, then add the following two inequalities to your MILP: $$NY \leq k$$ $$N-1+Y \geq k$$

As $$Y$$ is a binary variable, if $$k\lt N$$ then $$Y$$ must be $$0$$ to fulfill both inequalities. And when $$k=N$$ then $$Y$$ must be $$1$$ to fulfill both inequalities

• Thank you so much for your proposition. but when k=N (k<>0), with Y=0 both inequalities are true and with Y=1, the second inequality is False. Thanks again. – Sou Mar 26 at 14:51
• My apologies, I corrected the inequalities. – Maksim Mar 26 at 16:10
• Thank you Maksim for your solution. – Sou Mar 26 at 17:20
• HI, Is it possible to model: if X>k then Y=0, if X<k then Y=0, if X=k then Y=1. Any help is appreciated. – Sou Mar 27 at 12:41
• Is $X$ a constant ? – Maksim Mar 27 at 12:49

To your question in the comments: $$N$$ positive constant, $$k$$ positive integer constant with $$k\leq N$$, $$X$$ decision variable with $$0\leq X \leq N$$.

Add 3 binary variables $$r_1, r_2,r_3$$ together with the following constraints: \eqalign{ kr_1 & \leq X \\ X & \leq (1-r_1)(k-1)+r_1N \\ (k+1)(1-r_2) & \leq X\\ X & \leq kr_2+(1-r_2)N\\ 2r_3 & \leq r_1 +r_2 \\ r_1 +r_2 & \leq 1+ r_3 }

Then $$r_3 = 1$$ iff $$X=k$$, else $$r_3 = 0$$

• Thank you Maksim again for your response. I noticed that in case X>k or X<k it works perfectly, but when X=k, $$r_1$$ could be 0/1 and $$r_2$$ could be 0/1 and if they both are not 1 and 1 $$r_3$$ should be 0 and it is false. – Sou Mar 27 at 18:04
• Pls check again. – Maksim Mar 27 at 18:18
• Yes, it works in all cases!! Thank you so much. If possible, I would like to know if you find these solution just by intuition (experience) or there is a method that helps (I am relatively new and sometimes I get stuck!) . Thkx again. – Sou Mar 27 at 19:20