莫名其妙的"divide by zero"运行时警告与 numpy 屏蔽数组



我在Numpy中遇到一个除以零的运行时警告,我不明白为什么。

我说的是掩码数组的逆(元素方面),数组的有效值都不接近0。

在下面的公式中:ext和rpol是标量,而geocentp是一个掩码数组(所以temp和earth也将是掩码数组)。

temp = sqrt(1. - exct ** 2. * cos(geocentp)**2.)
print temp.count()
print temp.min(), temp.max()
Rearth = rpol / temp
print Rearth.count()
print Rearth.min(), Rearth.max()

打印输出为:

5680418
0.996616 0.999921
5680418
6357.09 6378.17

仍然得到警告:

seviri_lst_toolbox.py:1174: RuntimeWarning: divide by zero encountered in divide
  Rearth = rpol / temp

这很奇怪,对吧?掩码数组的通常行为是掩码值不被分割。如果一个有效值被零除,则该值将被屏蔽,而'count()'给出了除数前后有效值的确切数量,因此情况并非如此…

我迷路了……有人知道吗?


编辑:根据RomanGotsiy的回答,我可以通过更改掩码数组的浮点分子来消除警告:

Rearth = rpol * np.ma.ones(geocentp.shape, dtype=np.float32) / temp

但这显然不是理想的。这个矩阵(暂时的)造成了我的内存过载。有别的办法可以绕过这个吗?

我建议显示警告,因为rpol类型不是掩码数组。

查看我的控制台输出:

>>> import numpy as np, numpy.ma as ma
>>>
>>> x = ma.array([1., -1., 3., 4., 5., 6.])
>>> y = ma.array([1., 2., 0., 4., 5., 6.])
>>> print x/y
[1.0 -0.5 -- 1.0 1.0 1.0]
>>> # assign to "a" general numpy array
>>> a = np.array([1., -1., 3., 4., 5., 6.])
>>> print a/y
__main__:1: RuntimeWarning: divide by zero encountered in divide
[1.0 -0.5 -- 1.0 1.0 1.0]
>>> 

最新更新