C++ 维基百科上的线性插值代码 - 我不明白
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15345528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linear interpolation code on wikipedia - I don't understand it
提问by Johnny Pauling
I'm reading the following code (taken from here)
我正在阅读以下代码(取自此处)
void linear_interpolation_CPU(float2* result, float2* data,
float* x_out, int M, int N) {
float a;
for(int j = 0; j < N; j++) {
int k = floorf(x_out[j]);
a = x_out[j] - floorf(x_out[j]);
result[j].x = a*data[k+1].x + (-data[k].x*a + data[k].x);
result[j].y = a*data[k+1].y + (-data[k].y*a + data[k].y);
}
}
but I don't get it.
但我不明白。
Why isn't the result[y] calculated by using the
为什么结果[y]不是通过使用
formula?
公式?
回答by Richard
It is calculated that way.
是这样计算的。
Look at the first two lines:
看前两行:
int k = floorf(x_out[j]);
a = x_out[j] - floorf(x_out[j]);
The first line defines x0
using the floor function. This is because the article assumes a lattice spacing of one for the sample points, as per the line:
第一行定义x0
使用 floor 函数。这是因为文章假设样本点的晶格间距为 1,如以下行所示:
the samples are obtained on the 0,1,...,M lattice
Now we could rewrite the second line for clarity as:
现在为了清楚起见,我们可以将第二行重写为:
a = x_out[j] - k;
The second line is therefore x-x0
.
因此,第二行是x-x0
。
Now, let us examine the equation:
现在,让我们检查一下等式:
result[j].y = a*data[k+1].y + (-data[k].y*a + data[k].y);
Rewriting this in terms of y
, x
, and x0
gives:
来讲,改写本y
,x
和x0
得到:
y = (x-x0)*data[k+1].y + (-data[k].y*(x-x0) + data[k].y);
Let's rename data[k+1].y
as y1
and data[k].y
as y0:
让我们重命名data[k+1].y
为y1
和data[k].y
为Y0:
y = (x-x0)*y1 + (-y0*(x-x0) + y0);
Let's rearrange this by pulling out x-x0
:
让我们通过拉出重新排列它x-x0
:
y = (x-x0)*(y1-y0) + y0;
And rearrange again:
并再次重新排列:
y = y0 + (y1-y0)*(x-x0);
Again, the lattice spacing is important:
同样,晶格间距很重要:
the samples are obtained on the 0,1,...,M lattice
Thus, x1-x0
is always 1. If we put it back in, we get
因此,x1-x0
总是 1。如果我们把它放回去,我们得到
y = y0 + (y1-y0)*(x-x0)/(x1-x0);
Which is just the equation you were looking for.
这正是您正在寻找的等式。
Granted, it's ridiculous that the code is not written so as to make that apparent.
诚然,没有编写代码以使这一点显而易见,这很荒谬。