メインコンテンツへスキップ

How can I formulate a constraint that reflects that a variable can equal only -1 or 1?

回答済み

コメント

6件のコメント

  • 正式なコメント
    Simranjit Kaur
    • Gurobi Staff
    This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum, or try Gurobot, our chatbot interface offering instant, expert-level support.
  • Jaromił Najman
    • Gurobi Staff

    You can use a normal binary variable \(b \in \{0,1\}\) and define a new integer variable \(b_{-}\) as \(b_{-} = 2\cdot b -1\). \(b_-\) can only take values \(\{-1,1\}\).

     

    1
  • Kim Kestenboum
    • Gurobi-versary
    • First Comment
    • First Question

    Thank you!
    Another question if it is ok:

    How can I make a new variable y_ij that is 1 iff x_i == x_j ==1?

    0
  • Jaromił Najman
    • Gurobi Staff

    You can use Gurobi's addGenConstrAnd method for this.

    # construct yij = 1 <=> xi=1 and xj=1 constraint
    model.addGenConstrAnd(yij, [xi,xj],name="andconstr)

     

    1
  • Kim Kestenboum
    • Gurobi-versary
    • First Comment
    • First Question

    Hi, thanks for the answer, it really helped! 

    if I want in addition a variable z_ij which is 0 iff x_i == x_j ==0,

    can I write it this way? (of course xi,xj,zij  are binary variables)

    # construct zij = 0 <=> xi=0 and xj=0 constraint
    model.addGenConstrAnd(zij, [1-xi,1-xj],name="andconstr")
    0
  • Jaromił Najman
    • Gurobi Staff

    can I write it this way? (of course xi,xj,zij  are binary variables)

    # construct zij = 0 <=> xi=0 and xj=0 constraint
    model.addGenConstrAnd(zij, [1-xi,1-xj],name="andconstr")

    No, it is not directly possible, because the addGenConstrAnd method accepts only single variable objects, i.e., it does not accept LinExpr objects such as \(1-x_i\).

    You have to introduce 2 auxiliary binary variables \(y_i,y_j\) with \(y_i=1-x_i, y_j=1-x_j\) and then you can go with

    # construct zij = 0 <=> xi=0 and xj=0 constraint
    model.addConstr(yi == 1-xi)
    model.addConstr(yj == 1-xj)
    model.addGenConstrAnd(zij, [yi, yj],name="andconstr")
    1

投稿コメントは受け付けていません。