您的问题在于您正在尝试插值不在区间内的点,这将导致scipy.interpolate.interp1d
在尝试计算两个点之间的斜率时发出RuntimeWarning
警告(它在interpolate.py大约416行左右发生):
slope = (y_hi - y_lo) / (x_hi - x_lo)[:, None]
当你在区间内移动你的点时,会发生什么:
>>> import numpy as np
>>> from scipy.interpolate import interp1d
>>> x = np.array([ 5, 5, 10, 10, 10, 20])
>>> y = np.array([ 0, 0, 0, 0, 0, 30])
>>> X = np.array([5.1,5.1,5.1,6,10,11,20, 19.999])
>>> f = interp1d(x,y,'linear', 0, True, False, 0)
>>> Y = f(X)
[ 0. 0. 0. 0. 0. 3. 30. 29.997]
如果你绘制出它,你会看到一切都是有意义的:
![enter image description here](https://istack.dev59.com/D0m2r.webp)
这就是
interp1d
的工作原理:
- You pass
x
and y
to interp1d
and it creates a f
callable method
Then you pass the new x_new
values in which you want to evaluate f
and it performs the following steps:
Find where in the original data, the values to interpolate would be inserted.
>>> x_new_indices = np.searchsorted(x, X)
Clip x_new_indices so that they are within the range of x
indices and at least 1. Removes mis-interpolation of x_new[n] = x[0]
>>> x_new_indices = x_new_indices.clip(1, len(x)-1).astype(int)
Calculate the slope of regions that each x_new
value falls in.
>>> lo = x_new_indices - 1
>>> hi = x_new_indices
>>> x_lo = x[lo]
>>> x_hi = x[hi]
>>> y_lo = y[lo]
>>> y_hi = y[hi]
Calculate the actual value for each entry in x_new
.
>>> slope = (y_hi - y_lo) / (x_hi - x_lo)[:, None]
>>> y_new = slope*(x_new - x_lo)[:, None] + y_lo
[5 5 10 10 10 20]
变成[five 5 5 10 10 10 20]
。我的假设是出于微不足道的原因,新的重复项总是放在现有相同条目的左侧。然后您提到的进程,确保索引至少为1,重新排列该数组以变成[5 five 5 10 10 10 20]
。因此,斜率为“NaN”,因为“x_lo”=5且“x_hi”=5。最后,“y_new = NaN*0” =“NaN”。 - SkinnyTony