I want to write an INTERPOLATION function in JavaScript in order to be able to use Google Sheets instead of Excel for a number of purposes. In Excel, I have this user defined function written in VBA:
Function interpolate_1D(xreq As Single, x As Range, y As Range) As Single
' If we have variable y that is a function of x and have two ranges, x and y that give the values
'of y for particular values of x, we may need to find the value of y for a value of x not 'given in the table.
'For example, we may have power curve data for a wind turbine that gives the power output of a wind turbine
'for integer values of the wind speed. To find the output power at any other speed we could 'use this function, using as arguments:
'xreq: wind speed for which we wish to know the output power
'x: range containing the known wind speeds in ascending order
'y: range containing the known wind turbine powers
Dim pointer As Integer
Dim x0 As Single, y0 As Single, x1 As Single, y1 As Single
pointer = Application.Match(xreq, x, 1)
x0 = x(pointer)
x1 = x(pointer + 1)
y0 = y(pointer)
y1 = y(pointer + 1)
interpolate_1D = y0 + (xreq - x0) * (y1 - y0) / (x1 - x0)
End Function
I probably copied this from somewhere, such as Billo's book on Excel for Scientists and Engineers. It works very well, as does a 2D version of it that I wrote.
I am fairly new to JavaScript, and I can't at the moment see how to get it to do the equivalent of the Application.Match (xreq,x,1) line, where it looks through the range of known x values and finds the position of the largest value that is smaller than the search value xreq. Once i have that position, I can do everything else.
Any ideas?