NumPy interp()

The numpy.interp() function performs one-dimensional linear interpolation for a set of given data points. It estimates the value of a function at intermediate points based on known discrete values.

Syntax

</>
Copy
numpy.interp(x, xp, fp, left=None, right=None, period=None)

Parameters

ParameterTypeDescription
xarray_likeThe x-coordinates where interpolation is performed.
xp1-D sequence of floatsThe x-coordinates of known data points. Must be increasing unless period is specified.
fp1-D sequence of float or complexThe corresponding y-values of the known data points.
leftfloat or complex, optionalValue to return when x is less than the smallest value in xp. Default is fp[0].
rightfloat or complex, optionalValue to return when x is greater than the largest value in xp. Default is fp[-1].
periodNone or float, optionalDefines a periodic cycle for xp, normalizing values before interpolation.

Return Value

Returns an array of interpolated values corresponding to the given x values. The output has the same shape as x.


Examples

1. Basic Linear Interpolation

Performing interpolation at a given point using known data points.

</>
Copy
import numpy as np

# Define known data points
xp = np.array([1, 2, 3, 4, 5])  # x-coordinates
fp = np.array([2, 4, 6, 8, 10])  # Corresponding y-values

# Interpolate for a new x-value
x = 2.5
result = np.interp(x, xp, fp)

print("Interpolated value at x =", x, ":", result)

Output:

Interpolated value at x = 2.5 : 5.0