Search code examples
scipylinear-interpolation

How to find y value of interpolated spline at a desired x value?


How to extract the y value from spline at a desired x value. For example @ x= 0.25

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import splev, splrep
x = np.linspace(0, 10, 10)
y = np.sin(x)
spl = splrep(x, y)
x2 = np.linspace(0, 10, 5)
y2 = splev(x2, spl)
plt.plot(x, y, 'o', x2, y2)
plt.show()

enter image description here


Solution

  • Well, you are already doing this by calling splev(x,tck). This outputs an array with the y values at the given x values using the spline described by tck. (In your case, x is given by np.linspace() and tck is the output of np.splrep().)

    If you only want to know what the value at e.g. x=.25 is, you would write y3=splev(0.25, spl). Maybe take a look at the documentation for more details: https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.splev.html