-1

I am currently working on a optimization problem on GUROBI.All my variables are of binary type.I have a variable y which is equal to the absolute of difference of two binary decision variables.However,when i tried to use the abs() function,i get this output.

TypeError: bad operand type for abs(): 'gurobipy.LinExpr'

Therefore,i am now squaring the difference (since difference is always -1,0 or 1). But this causes higher optimization time(quadratic expressions after squaring). Is there any alternative to this?

Also,there is a case(not binary variables) where the difference of two variables may not be -1,0 or 1.How do i take the absolute in this case?

Suman L
  • 1
  • 3

1 Answers1

1

y=|x1-x2| for binary variable is the same as y = x1 xor x2. This can be written as:

y <= x1+x2 
y >= x1-x2 
y >= x2-x1 
y <= 2-x1-x2

(see here).

When x1,x2 are continuous variables between 0 and U you can write:

y1-y2 = x1-x2
y = y1+y2
y1 <= delta*U
y2 <= (1-delta)*U
y1>=0
y2>=0
delta in {0,1}

In many cases this can be simplified.

Erwin Kalvelagen
  • 15,677
  • 2
  • 14
  • 39