numpy数组划分浮点错误不一致行为?

时间:2015-11-04 17:16:07

标签: python arrays numpy floating-point

简而言之,我正在分割一个numpy数组的float32s,导致单个值出现溢出错误。但是,如果我只将值除以(而不是数组),则没有错误。我在IPython Notebook中使用Python2.7。

import numpy as np
np.seterr('warn')

我的数组名为kone

masked_array(data = [  1.20134726e-02   1.27720274e-03   6.29213825e-03   1.30603567e-03
   5.76360899e-23],
             mask = False,
       fill_value = 0.0)

那么:

print 1, 1./kone**2 # floating point error for the last element
print 2, np.divide(1., kone**2)
print 3, 1./kone[4]**2
print 4, np.divide(1.,kone[4]**2)
print 5, np.divide(1.,np.array([kone[4]**2]))
print 6, 1./np.array([kone[4]])**2
print 7, np.divide(1, np.array([kone[4]])**2)

OUTPUT:

1 [6928.87744140625 613028.0 25258.263671875 586259.5 inf]
2 [6928.87744140625 613028.0 25258.263671875 586259.5 inf]
3 3.01030832259e+44
4 3.01030832259e+44
5 [  3.01030832e+44]
6 [ inf]
7 [ inf]

-c:12: RuntimeWarning: overflow encountered in divide
-c:13: RuntimeWarning: overflow encountered in divide
-c:17: RuntimeWarning: underflow encountered in square
-c:17: RuntimeWarning: overflow encountered in divide
-c:18: RuntimeWarning: underflow encountered in square

更令人困惑的是,如果我如上所述arr = kone.copy()print,则输出与预期相同。但是,如果我创建一个与kone具有相同值的新数组:

arr = np.ma.array([1.20134726e-02, 1.27720274e-03, 6.29213825e-03, 1.30603567e-03, 5.76360899e-23], mask=False, fill_value=0.0)
print kone
print arr
print np.isclose(kone,arr)

print 1, 1./arr[0:5]**2 
print 2, np.divide(1., arr[0:5]**2)
print 3, 1./arr[4]**2
print 4, np.divide(1.,arr[4]**2)
print 5, np.divide(1.,np.array([arr[4]**2]))
print 6, 1./np.array([arr[4]])**2
print 7, np.divide(1, np.array([arr[4]])**2)

OUTPUT:

    [  1.20134726e-02   1.27720274e-03   6.29213825e-03   1.30603567e-03
   5.76360899e-23]
[0.0120134726 0.00127720274 0.00629213825 0.00130603567 5.76360899e-23]
[ True  True  True  True  True]
1 [6928.87737841692 613028.0078115561 25258.263370509678 586259.5403880107
 3.010308326172682e+44]
2 [6928.87737841692 613028.0078115561 25258.263370509678 586259.5403880107
 3.010308326172682e+44]
3 3.01030832617e+44
4 3.01030832617e+44
5 [  3.01030833e+44]
6 [  3.01030833e+44]
7 [  3.01030833e+44]

突然间没有浮点错误?我不知道最后一个例子与之前的例子有何不同。更重要的是,我不知道6,7的操作与示例1中的3,4,5 有何不同?

编辑:见评论。

0 个答案:

没有答案