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

标签 c++ mathematical-optimization cplex

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

最佳答案

我在 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);
}

关于c++ - 如何线性化两个浮点变量的乘积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49021401/

相关文章:

c++ - 将较小整数的最大值分配给较大整数

kotlin - ojAlgo-在优化中将变量表示为边界?

c++ - 我的初始化有什么问题?

c++ - 在 CPLEX 中从 IloBoolVarArray 解析到 Bool 的问题

C++:将自身结构的地址作为参数传递给 pthread_create 时出错:什么覆盖了我的数据?

c++ - 时序算法 : clock() vs time() in C++

php - MySQL 存储过程中的数学公式返回不正确的值

algorithm - 多源多目的地最短路径

mathematical-optimization - 为什么AMPL无法解决优化失败

c++ - 什么是函数的左值引用?