Skip to content
Advertisement

Linear interpolation library with php [closed]

I need to interpolate points with php, do you know any library for that? A traditional search did not allow me to find any that good results.

I have a table with values in columns x and y.

X          Y
10       676
20       894
30      1100
40      1200
50      1000

I was wondering if there is a function that can help with linear interpolation. For example, I want the interpolated value of Y that corresponds to X=35.

Thanks

Advertisement

Answer

That’s simple math – no need to use any library at all.

If you want the Y value of X, you have to find the greatest value smaller than X (x0) and the lowest value greater than X (x1). If this two values are equal, you don’t have to do anything and just return the Y value in your table.

Otherwise, take the two corresponding Y values (y0 and y1) and do a interpolation with them.

d = (x - x0) / (x1 - x0) // value in the range of [0; 1]
y = y0 * (1 - d) + y1 * d // your interpolated value

in your case of x = 35 => x0 = 30, x1 = 40

d = (35 - 30) / (40 - 30) // 0.5
y = 1100 * (1 - 0.5) + 1200 * 0.5 // 1150
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement