如何线性化两个浮点变量的乘积

时间:2018-02-28 03:15:39

标签: c++ mathematical-optimization cplex

我想线性化两个浮点变量的乘积。假设模型具有乘积x * y,其中x和y是浮点数,0 <= x <= 1且0 <= y <= 1.如何线性化该乘积?

1 个答案:

答案 0 :(得分:2)

我在OPL / CPLEX here中举了一个例子。

你能做的就是记住

4*x*y=(x+y)*(x+y)-(x-y)(x-y)

因此,如果您执行变量X = x + y和Y = x-y

x*y

变为

1/4*(X*X-Y*Y)

是可分离的。

然后你可以通过分段线性函数插入函数x * x:

// y=x*x interpolation



int sampleSize=10000;
float s=0;
float e=100;

float x[i in 0..sampleSize]=s+(e-s)*i/sampleSize;

int nbSegments=20;

float x2[i in 0..nbSegments]=(s)+(e-s)*i/nbSegments;
float y2[i in 0..nbSegments]=x2[i]*x2[i];

float firstSlope=0;
 float lastSlope=0;

 tuple breakpoint // y=f(x)
 {
  key float x;
  float y;
 }

 sorted { breakpoint } breakpoints={<x2[i],y2[i]> | i in 0..nbSegments};

 float slopesBeforeBreakpoint[b in breakpoints]=
 (b.x==first(breakpoints).x)
 ?firstSlope
 :(b.y-prev(breakpoints,b).y)/(b.x-prev(breakpoints,b).x);

 pwlFunction f=piecewise(b in breakpoints)
 { slopesBeforeBreakpoint[b]->b.x; lastSlope } (first(breakpoints).x, first(breakpoints).y);

 assert forall(b in breakpoints) f(b.x)==b.y;

 float maxError=max (i in 0..sampleSize) abs(x[i]*x[i]-f(x[i]));
 float averageError=1/(sampleSize+1)*sum (i in 0..sampleSize) abs(x[i]*x[i]-f(x[i]));

 execute
{
writeln("maxError = ",maxError);
writeln("averageError = ",averageError);
}

dvar float a in 0..10;
dvar float b in 0..10;
dvar float squareaplusb;
dvar float squareaminusb;

maximize a+b;
dvar float ab;
subject to
{
    ab<=10;
    ab==1/4*(squareaplusb-squareaminusb);

    squareaplusb==f(a+b);
    squareaminusb==f(a-b);
}