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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:17:48  来源:igfitidea点击:

Linear interpolation code on wikipedia - I don't understand it

c++cinterpolation

提问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]不是通过使用

enter image description here

在此处输入图片说明

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 x0using 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 x0gives:

来讲,改写本yxx0得到:

y = (x-x0)*data[k+1].y + (-data[k].y*(x-x0) + data[k].y);

Let's rename data[k+1].yas y1and data[k].yas y0:

让我们重命名data[k+1].yy1data[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-x0is 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.

诚然,没有编写代码以使这一点显而易见,这很荒谬。