Linear interpolation code on Wikipedia - I don't understand this

I am 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 do not understand.

Why the result [y] is not calculated using

enter image description here

formula?

+7
source share
1 answer

It is calculated in this 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 due to the fact that the article assumes that the distance between the cells is equal to unity for the sampling points in accordance with the line:

 the samples are obtained on the 0,1,...,M lattice 

Now we can rewrite the second line for clarity as:

 a = x_out[j] - k; 

Therefore, the second line is x-x0 .

Now consider the equation:

 result[j].y = a*data[k+1].y + (-data[k].y*a + data[k].y); 

Rewriting this through y , x , and x0 gives:

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

Rename data[k+1].y as y1 and data[k].y as y0:

 y = (x-x0)*y1 + (-y0*(x-x0) + y0); 

Rearrange this value by pulling x-x0 :

 y = (x-x0)*(y1-y0) + y0; 

And rebuild again:

 y = y0 + (y1-y0)*(x-x0); 

Again, the distance between the grilles is important:

 the samples are obtained on the 0,1,...,M lattice 

Thus, x1-x0 always 1. If we return it back, we get

 y = y0 + (y1-y0)*(x-x0)/(x1-x0); 

This is just the equation you were looking for.

Of course, it’s funny that the code is not written to make it obvious.

+11
source

All Articles