numpy掩码数组中不可解释的“除以零”RuntimeWarning

1 投票
1 回答
1439 浏览
提问于 2025-04-18 13:40

我在使用Numpy时遇到了一个“除以零”的运行时警告,但我搞不懂为什么会这样。

我在对一个被屏蔽的数组进行逐元素的取倒数操作,而这个数组中有效值都离零很远。

在下面的公式中:exct和rpol是标量(就是普通的数字),而geocentp是一个被屏蔽的数组(所以temp和Rearth也会是被屏蔽的数组)。

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

但这显然不是一个理想的解决方案。这个临时创建的矩阵占用了我太多的内存。有没有其他方法可以解决这个问题?

1 个回答

1

我认为这个警告出现是因为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]
>>> 

撰写回答