带有numpy掩码数组的令人费解的“除以零”运行时警告

2024-09-28 05:18:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我说的是一个屏蔽数组的逆(elementwise),数组的有效值都不接近0。在

在下面的公式中:exct和rpol是标量,geocentp是一个屏蔽数组(因此temp和rerth也将被屏蔽数组)。在

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()

打印输出为:

^{pr2}$

但我还是得到了警告:

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

但这显然并不理想。这个矩阵(暂时)造成了我的记忆过载。有没有别的办法可以解决这个问题?在


Tags: 警告countnp数组mintempmax屏蔽
1条回答
网友
1楼 · 发布于 2024-09-28 05:18:32

我建议显示警告是因为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]
>>> 

相关问题 更多 >

    热门问题