gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:29:54 25 4
gpt4 key购买 nike

我想线性化两个浮点变量的乘积。假设模型具有乘积 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com