Difference between quadratic and 2nd order spline interpolation in scipy

♀尐吖头ヾ 提交于 2019-12-23 20:40:46

问题


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, (‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic, ‘cubic’ where ‘slinear’, ‘quadratic’ and ‘cubic’ refer to a spline interpolation of 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


回答1:


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


来源:https://stackoverflow.com/questions/46637605/difference-between-quadratic-and-2nd-order-spline-interpolation-in-scipy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!