为什么numpy.exp()在这种情况下给出溢出警告?



我有以下可重现的脚本:

import numpy as np
c0, c1 = 0.000032, 3
S_test = np.ones((3,3), dtype=float)*300000
S_test[1,1] = 2000

np.where(S_test > 2000, 1, 1 - 1 / np.exp((c0 * S_test) ** c1) )
RuntimeWarning: overflow encountered in exp
array([[1.00000000e+00, 1.00000000e+00, 1.00000000e+00],
[1.00000000e+00, 2.62109643e-04, 1.00000000e+00],
[1.00000000e+00, 1.00000000e+00, 1.00000000e+00]])

我试图弄清楚 1(为什么我会收到这个溢出错误以及 2( 如何以一种不只是忽略它的方式处理它,因为我不完全确定首先忽略它的后果是什么。

np.where()应首先识别S_test > 2000的位置,然后为这些值返回 1,或者,如果此条件不成立np.where()则应返回1 - 1 / np.exp((c0 * S_test) ** c1)

我尝试单独计算1 - 1 / np.exp((c0 * 2000) ** c1),这评估很好,正如我预期的那样。

任何见解都会很棒。

np.where 计算这两个操作数。

如果你真的想避免警告,你可以做这样的事情:https://github.com/scipy/scipy/blob/master/scipy/_lib/_util.py#L31

您会收到错误,因为np.where的所有参数都已完全计算。您可以这样做:

S_test_capped = np.where(S_test > 2000, 2000, S_test)
np.where(S_test > 2000, 1, 1 - 1 / np.exp((c0 * S_test_capped) ** c1) )

或者只是将警告静音:

old_settings = np.seterr(over='ignore')
np.where(S_test > 2000, 1, 1 - 1 / np.exp((c0 * S_test) ** c1) )
np.seterr(**old_settings) # restore warning settings

最新更新