RuntimeWarning:在cosh——Python中遇到溢出.这是什么意思?



我正在运行以下计算:

N = 2**15
dx = 0.1
x = np.arange(-N/2,N/2)
u0 = np.zeros([N, 1])
L = N * dx
x0 = x[1] + 2 * delta
delta = 15
while x0 < L - delta:
l1 = 1.267;
x0 = x0 + delta
r = 1/(l1*np.cosh(x)**2)
u0 = r + u0

本质上,当x0

翻译成MATLAB可以很好地工作,但python给了我这个错误:

RuntimeWarning: cosh溢出
r = 1/(l1*np.cosh(x)**2)

cosh长得非常大:

In [70]: np.cosh(2**10)
<ipython-input-70-c4511154ec1e>:1: RuntimeWarning: overflow encountered in cosh
np.cosh(2**10)
Out[70]: inf

为什么你的x这么宽?在大部分范围内,cosh的倒数为0。

In [72]: N=2**15; x = np.arange(-N/2,N/2)
In [73]: len(x)
Out[73]: 32768
In [74]: r = 1/(np.cosh(x)**2)
<ipython-input-74-404fbe3be390>:1: RuntimeWarning: overflow encountered in cosh
r = 1/(np.cosh(x)**2)
<ipython-input-74-404fbe3be390>:1: RuntimeWarning: overflow encountered in square
r = 1/(np.cosh(x)**2)
In [75]: r[:10]
Out[75]: array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
In [77]: np.sum(r<1e-16)
Out[77]: 32729

查看x的+-20范围

In [88]: x = np.arange(-20,20)
In [89]: r = 1/(np.cosh(x)**2)
In [90]: r
Out[90]: 
array([1.69934170e-17, 1.25565312e-16, 9.27809132e-16, 6.85563373e-15,
5.06566622e-14, 3.74304919e-13, 2.76576004e-12, 2.04363561e-11,
...
1.00000000e+00, 4.19974342e-01, 7.06508249e-02, 9.86603717e-03,
...
1.51005382e-10, 2.04363561e-11, 2.76576004e-12, 3.74304919e-13,
5.06566622e-14, 6.85563373e-15, 9.27809132e-16, 1.25565312e-16])

抑制警告

In [148]: x=np.array([-2**15,-2**4,0,2**4,2**15])
In [155]: np.cosh(x)
<ipython-input-155-1e743139b88e>:1: RuntimeWarning: overflow encountered in cosh
np.cosh(x)
Out[155]: 
array([           inf, 4.44305526e+06, 1.00000000e+00, 4.44305526e+06,
inf])
In [156]: 1/(np.cosh(x)**2)
<ipython-input-156-5cf76600c0c7>:1: RuntimeWarning: overflow encountered in cosh
1/(np.cosh(x)**2)
Out[156]: 
array([0.00000000e+00, 5.06566622e-14, 1.00000000e+00, 5.06566622e-14,
0.00000000e+00])

警告不会阻止您获取有用的值。这是一个警告,而不是错误.

但是可以抑制警告。路上有errstate:

In [157]: with np.errstate(over='ignore'):
...:     y = 1/(np.cosh(x)**2)
...: 
In [158]: y
Out[158]: 
array([0.00000000e+00, 5.06566622e-14, 1.00000000e+00, 5.06566622e-14,
0.00000000e+00])

np.seterr也可以使用,但它将改变整个脚本的处理,而不仅仅是这个上下文。所以首选with np.errstate

一定要花时间阅读文档。

In [159]: np.geterr()
Out[159]: {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}

还有一个warnings模块

为什么我不能't抑制numpy警告

最新更新