【问题标题】:Inexplicable "divide by zero" RuntimeWarning with numpy masked arrays带有 numpy 掩码数组的莫名其妙的“除以零”RuntimeWarning
【发布时间】:2014-09-08 04:43:20
【问题描述】:

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

我说的是屏蔽数组的逆(按元素),并且数组的所有有效值都不接近 0。

在以下公式中: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

但这显然并不理想。这个矩阵(暂时)创建了我的记忆。还有其他方法可以解决这个问题吗?

【问题讨论】:

标签: python numpy divide-by-zero


【解决方案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]
>>> 

【讨论】:

  • 这似乎确实是问题所在。 rpol 是一个浮点数。我怎么能解决这个(愚蠢的)问题?
猜你喜欢
  • 2012-05-19
  • 1970-01-01
  • 1970-01-01
  • 2013-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-04
相关资源
最近更新 更多