Reputation: 917
I am writing functions that will calculate 1d interpolations in python using scipy.interpolate
function. using help from documentation I wrote 2 different functions for cubic and cubic spline interpolation
# calculate cubic interpolation
def linear_interpolation(x):
linear = interpolate.interp1d(support_x, support_y, 'cubic')
return linear(x)
# calculate cubic spline interpolation
def cubic_spline_interpolation(x):
tck = interpolate.splrep(support_x, support_y)
return interpolate.splev(x, tck)
I am a bit confused about the methods here. If I use interpolate.interp1d(support_x, support_y, 'cubic')
, is that different from cubic spline
method? Also what is the difference between kind = 'quadratic'
and second order spline
?
The documentation says:
‘zero’, ‘slinear’, ‘quadratic’ and ‘cubic’ refer to a spline interpolation of zeroth, first, second or third order
so why do I have to write different function for cubic spline instead of just changing it to kind='cubic'
?
Upvotes: 3
Views: 4106
Reputation:
They both return the same splines, although internally, the implementation is not the same (interp1d
is more recent and has greater Python code percentage, compared to splrep
which is nearly all Fortran code). "Quadratic" means the same as 2nd degree, and "cubic" is 3rd degree. Some distinction:
splrep
and its close relative UnivariateSpline are more feature-rich spline construction routines; they allow for a smoothing parameter which creates non-interpolating spline.interp1d
may be simpler to use if you do not require smoothing. In any event, this is far from the only instance of redundant functionality in SciPy. New methods and parameters are added, but old ones are kept for backward compatibility.
Historical note: in older versions of SciPy (e.g., 0.15.1), interp1d
returned rather different splines, of lower quality compared to splrep
(the first revision of this answer was based on version 0.15.1). In the current version 0.19.1 this issue is no longer present: both return the same spline. Here is a demonstration:
import numpy as np
from scipy.interpolate import interp1d, splrep, splev
x = np.linspace(0, 6, 7)
y = np.array([3, 1, 4, 1, 5, 5, 2]) # some data
xx = np.linspace(0, 6, 100) # evaluation points
y1 = interp1d(x, y, kind='cubic')(xx)
y2 = splev(xx, splrep(x, y, k=3))
print(np.abs(y1-y2).max())
y1 = interp1d(x, y, kind='quadratic')(xx)
y2 = splev(xx, splrep(x, y, k=2))
print(np.abs(y1-y2).max())
Output shows that both routines agree within typical numerical errors.
2.6645352591e-15
1.7763568394e-15
Upvotes: 5