In PulP modeling, I have an integer variable s that can take on values 0, 1, or 2. I want a binary indicator variable y such that y=1 if s=0 or s=2, and y=0 if s=1.
I tried defining three binary variables z1, z2, and y, and setting up these constraints:
z1 <= s <= 2 * z1
2*z2 <= s
s < 2*z2 + 2
y = z1 * (1 - z2)
Essentially, z1=1
means s>0
, and z2=0
means s<2
. Hence y=1
means s=1
, and y=0
means s=0
or 2
.
However, this makes y non-linear, since it is a product of 2 variables.
Is there a way to define y using only linear constraints?
In PulP modeling, I have an integer variable s that can take on values 0, 1, or 2. I want a binary indicator variable y such that y=1 if s=0 or s=2, and y=0 if s=1.
I tried defining three binary variables z1, z2, and y, and setting up these constraints:
z1 <= s <= 2 * z1
2*z2 <= s
s < 2*z2 + 2
y = z1 * (1 - z2)
Essentially, z1=1
means s>0
, and z2=0
means s<2
. Hence y=1
means s=1
, and y=0
means s=0
or 2
.
However, this makes y non-linear, since it is a product of 2 variables.
Is there a way to define y using only linear constraints?
Share Improve this question edited Mar 18 at 18:53 Chait 1,3713 gold badges22 silver badges37 bronze badges asked Mar 17 at 16:27 cmukidcmukid 31 silver badge1 bronze badge 1- 1 Maybe I'm misunderstanding the problem here but it sounds like y = 0 if s == 1 else 0 – Adon Bilivit Commented Mar 17 at 16:37
3 Answers
Reset to default 1My suggestion sticks with constraint types available to Linear Programming. Therefore, non-linear constraints and modulo operators are not available.
You could introduce y
and s1
as binary variables.
The constraints:
y == 1 - s + 2*s1
0 <= y <= 1
0 <= s1 <= 1
Three cases for s:
s = 0: s1 = 0, y = 1
s = 1: s1 = 0, y = 0
s = 2: s1 = 1, y = 1
One line, using the modulo operator:
y = (s + 1) % 2
Nine non-whitespace characters.
You could always use the last bit!
y=~s&1