gpt4 book ai didi

python - Scipy interp1d 和无穷大

转载 作者:行者123 更新时间:2023-12-01 04:20:19 24 4
gpt4 key购买 nike

当使用 scipy.interpolate.interp1d 线性插值时,我遇到以下行为:

from scipy.interpolate import interp1d
import numpy as np
x = [0,1,2,3,4]
y = [np.inf, 10, 12, 11, 9]
interpolated_function = interp1d(x,y)

现在,当然插值在 [0,1) 中没有明确定义,但在 1 中我希望它能够被定义。但是:

In[2]:  interpolated_function(1.)
C:\WinPython27\python-2.7.10\lib\site-packages\
scipy\interpolate\interpolate.py:469:
RuntimeWarning: invalid value encountered in add
y_new = slope*(x_new - x_lo)[:, None] + y_lo
Out[2]: array(nan)

In[3]: interpolated_function(1.000000000000001)
Out[3]: array(10.000000000000002)

这是预期的行为吗? 1 处的插值函数不应该被评估为 10,因为这是传递给 interp1d 的完全有效的数据点?

最佳答案

interp1d 没有特殊情况的 naninf。对于 kind="linear" 它只是在包含输入值的区间上使用您收到的错误消息中打印的公式。

由于精确相等在浮点中不可靠,因此通过在 1.0 上对其进行评估,您依赖于将其分类为 (0, 1) 或 (1, 2) 的实现细节。

例如,

In [26]: np.interp(1, x, y)
Out[26]: 10.0

In [32]: interp1d(x, y, kind='slinear')(1.)
Out[32]: array(10.0)

在 scipy 的 future 版本中,行为将取决于 fill_value。 (在当前的开发版本中,您可以使用 fill_value="extrapolate"。)

最好的办法是在用户端过滤掉非有限数。

In [33]: x, y = map(np.asarray, (x, y))

In [34]: mask = np.isfinite(x) & np.isfinite(y)

In [35]: ii = interp1d(x[mask], y[mask])

In [36]: ii(1.)
Out[36]: array(10.0)

关于python - Scipy interp1d 和无穷大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33824186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com