How to get absolute value of a linear expression?

时间:2016-07-11 23:15:29

标签: mathematical-optimization gurobi

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?

1 个答案:

答案 0 :(得分:1)

二进制变量的

y=|x1-x2|y = x1 xor x2相同。这可以写成:

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

(见here)。

x1,x2是0到U之间的连续变量时,您可以写:

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

在许多情况下,这可以简化。