The NumPy interp() function allows you to get the one-dimensional linear interpolation to a function with the provided discrete data points (xp, fp), evaluated at x.
Function Syntax
The function syntax is as shown below:
1 | numpy.interp(x, xp, fp, left=None, right=None, period=None) |
Parameters
The function parameters are discussed below:
- x – defines the x-coordinates at which the interpolated values are evaluated.
- xp – represents the x-coordinates of the data points.
- fp – represents the y-coordinates of the data points. They must be of the same length as xp.
- left – defines the value to return for x < xp[0].
- right – defines the value to return for x > xp[-1].
- period – specifies the period for the x-coordinates.
Resource: https://en.wikipedia.org/wiki/Linear_interpolation
Return Value
The function returns the interpolated values with the same shape as the input (x).
Example
The following example illustrates how to use the interp() function in NumPy.
1 2 3 4 5 6 | # import numpy import numpy as np x = 1.4 xp = [6,4,2] fp = [1,2,3] print(np.interp(x, xp, fp)) |
The code above should return:
1 | 1.0 |
Example #2
Consider the code below with periodic coordinates.
1 2 3 4 | x = [0, 1.8, 2.4, 1., 2] xp = [100, 90, 45, 33] fp = [4,3,2,1] print(np.interp(x, xp, fp, period=240)) |
The above code should return:
1 | [1.57225434 1.54104046 1.53063584 1.55491329 1.53757225] |
Conclusion
This article covers the basics of the interp function in NumPy. Feel free to explore the docs for more.
Happy coding!!