Q-Logo 我的学习笔记分享

Entries for tag "ke-xue-ji-suan"

Python一维线性插值(内插和外插)

Python的numpy和scipy包都提供了线性插值的功能,尤其是后者,还支持外插。

numpy.interp内插例子:

>>> xp = [1, 2, 3]
>>> fp = [3, 2, 0]
>>> np.interp(2.5, xp, fp)
1.0
>>> np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp)
array([3. , 3. , 2.5 , 0.56, 0. ])

scipy.interpolate.interp1d内插和外插例子:

from scipy.interpolate import interp1d

>>> x = [1, 2, 3]

>>> y = [3, 2, 0]

>>> f = interp1d(x,y,fill_value=(3,0),bounds_error=False) # 线性内插

>>> f([0, 1, 1.5, 2.72, 3.14])

array([3. , 3. , 2.5 , 0.56, 0. ])

>>> fe = interp1d(x,y, fill_value='extrapolate') # 线性内插+外插

>>> fe([0, 1, 1.5, 2.72, 3.14])

array([ 4. , 3. , 2.5 , 0.56, -0.28])