Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL function table interpolation

I have an SQL table of (x,y) values.

x     y
0.0   0.0
0.1   0.4
0.5   1.0
5.0   2.0
6.0   4.0
8.0   4.0
10.0  5.0

The x column is indexed. I am using sqlite.

My ultimate goal is to get a y(x) for any x value. I will use linear interpolation using table values. Similar as shown in the plot below.

enter image description here

Is there a way to perform the linear interpolation directly using a select query? Otherwise getting the interval values where the x belongs, would be enough.

Is there a query that will give me the last smaller and the first bigger pair of a given x, so that I can compute the interpolated y(x) value?

For example if x=2.0 to get:

0.5   1.0
5.0   2.0

In case x is out of the table to get the two first/last values to perform an extrapolation.

For example if x=20.0 to get:

8.0   4.0
10.0  5.0
like image 451
ztik Avatar asked Mar 09 '26 13:03

ztik


2 Answers

It would be hard to do this in plain SQLLite, without analytical functions. In more complex SQL engines, You could use LEG and LEAD analytical functions for obtaining set of pairs You want easily enough. In SQLLite though, I would create two cursors, like those:

Cursor C1:

SELECT 
    x,y
FROM
    table
WHERE
    x>=2
ORDER BY
    x asc
;

Cursor C2:

SELECT 
    x,y
FROM
    table
WHERE
    x<=2
ORDER BY
    x desc
;

And perform rest of operations in other language - fetching once from both, or if one cursor do not return value, twice from the other. Also, some additional exceptions need to be handled - what if Your set have less than two values. Or if You have given X in Your set - You do not need interpolata at all... And so on.

like image 130
T.Z. Avatar answered Mar 12 '26 06:03

T.Z.


I would go with a simple substraction.

You are looking to the two nearest input so :

SELECT x, y 
FROM my_table
ORDER BY Abs(:val - x)
LIMIT 2

However this will lead to a full table scan.

like image 27
Nemeros Avatar answered Mar 12 '26 06:03

Nemeros