scipy interp1d 无法处理无限数

问题描述

我有一个 y = ax + b 函数,其中 a 和 b 是常量。我想找出y的最大值。我们知道如果a = 0那么y = b,否则y的最大值是无穷大。所以我尝试使用 scipy.interpolate.interp1d 来得到答案。运行下面的示例 2 将导致错误消息。

from scipy import interpolate
import math

# example 1 (works): y = x + 0
func1 = interpolate.interp1d([1,2],[1,fill_value='extrapolate')
print(func1(math.inf)) # this will print inf as expected

# example 2 (doesn't work): y = 1
func2 = interpolate.interp1d([1,1],fill_value='extrapolate')
print(func2(math.inf)) # I'm expecting 1,however it showed array(nan)

错误信息:

RuntimeWarning: invalid value encountered in multiply
  y_new = slope*(x_new - x_lo)[:,None] + y_lo

编辑: 用非常大的数字替换 math.inf,比如 func2(9223372036854775807) 也可以。

解决方法

这是由于 IEEE 754 标准中定义的使用 inf 进行算术的规则。规则是:

  1. 对于任何 x > 0,我们有 x * inf -> inf
  2. 0 * inf = nan
  3. 对于任何 x < 0,我们有 x * inf -> -inf

讨论了规则 2 的原因elsewhere

如果我们检查您的错误消息中的代码行,我们可以弄清楚发生了什么:

y_new = slope * (x_new - x_lo)

括号中的术语对于您的两个示例都具有 inf 值。在您的第一个示例 slope = 1 中,我们应用第一个规则并获得 1 * inf -> inf。但是,在您的第二个示例 slope = 0 中,我们必须使用第二个规则,我们得到 0 * inf -> nan