Python

NumPy Np.Interp()

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:

  1. x – defines the x-coordinates at which the interpolated values are evaluated.
  2. xp – represents the x-coordinates of the data points.
  3. fp – represents the y-coordinates of the data points. They must be of the same length as xp.
  4. left – defines the value to return for x < xp[0].
  5. right – defines the value to return for x > xp[-1].
  6. 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!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list