In SciPy, there are numerous interpolation function that return a function, e.g., Akima1DInterpolator. I’d like to have the same for a simple linear interpolator. interp1d does the trick, but is deprecated. What can I replace it with?
import numpy as np
from scipy.interpolate import Akima1DInterpolator, interp1d
import matplotlib.pyplot as plt
t = np.linspace(0.0, 1.0, 4)
y = np.array([1.0, 0.8, 0.7, 1.2])
# ak = Akima1DInterpolator(t, y)
# works, but deprecated:
ak = interp1d(t, y, kind="linear")
tt = np.linspace(0.0, 1.0, 200)
yy = ak(tt)
plt.plot(tt, yy)
plt.plot(t, y, "x")
plt.gca().set_aspect("equal")
plt.show()
>Solution :
According to this table, SciPy recommends np.interp for a 1 dimensional linear problem. This can be converted into a function returning a function like so:
def create_linear_interpolator(t, y):
def inner(x):
return np.interp(x, t, y)
return inner
ak = create_linear_interpolator(t, y)
The ak object can then be called to interpolate any specific x value.
Alternatively, this is a bit of a hack, but a first-order spline is equivalent to linear interpolation.
ak = make_interp_spline(t, y, k=1)
