最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Binary indicator variable related to another variable - Stack Overflow

programmeradmin2浏览0评论

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
Add a comment  | 

3 Answers 3

Reset to default 1

My 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
发布评论

评论列表(0)

  1. 暂无评论