重复调用时,numpy.reciprocal返回不同的值

时间:2018-03-24 00:24:01

标签: python numpy floating-point

我有一个numpy数组ssh_sum

>>> ssh_sum
array([[ 0.,  2.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  2.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.,  2.]])

我想计算此数组中的逐元素倒数值。当我反复调用np.reciprocal时,Numpy会返回不同的值:

>>> ssh_sum
array([[ 0.,  2.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  2.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.,  2.]])
>>> np.reciprocal(ssh_sum, where=(ssh_sum > 0.))
array([[  6.90326535e-310,   5.00000000e-001,   1.00000000e+000,
          0.00000000e+000,   1.07034283e-296,   1.33666925e+241],
       [  4.74783847e-309,   1.45260789e-296,   1.00000000e+000,
          5.00000000e-001,   2.13436228e-287,  -3.13188338e-294],
       [  4.85105226e-309,   1.08690709e+171,   4.09521901e+149,
          1.00000000e+000,   2.82730247e-311,   5.00000000e-001]])
>>> np.reciprocal(ssh_sum, where=(ssh_sum > 0.))
array([[ inf,  0.5,  1. ,  inf,  inf,  inf],
       [ inf,  inf,  1. ,  0.5,  inf,  inf],
       [ inf,  inf,  inf,  1. ,  inf,  0.5]])
>>> np.reciprocal(ssh_sum, where=(ssh_sum > 0.))
array([[  6.90326535e-310,   5.00000000e-001,   1.00000000e+000,
          0.00000000e+000,   1.07034283e-296,   1.33666925e+241],
       [  4.74783847e-309,   1.45260789e-296,   1.00000000e+000,
          5.00000000e-001,   2.13436228e-287,  -3.13188338e-294],
       [  4.85105226e-309,   1.08690709e+171,   4.09521901e+149,
          1.00000000e+000,   2.82730247e-311,   5.00000000e-001]])
>>> np.reciprocal(ssh_sum, where=(ssh_sum > 0.))
array([[ inf,  0.5,  1. ,  inf,  inf,  inf],
       [ inf,  inf,  1. ,  0.5,  inf,  inf],
       [ inf,  inf,  inf,  1. ,  inf,  0.5]])

知道这里发生了什么吗?我使用的是Python 3.4.5和numpy 1.13.3。

1 个答案:

答案 0 :(得分:3)

不只是reciprocal;使用where参数时会出现问题。我已经能够使用numpy的主分支重现问题(np.__version__'1.15.0.dev0+c093997'),其功能包括abssign,{{1 },add

如果您阅读了numpy" ufuncs"的文档字符串。仔细并正确地解释它们,你会发现行为不是一个错误。以下是subtract docstring:

的相关说明
numpy.reciprocal

特别注意:

  • out : ndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or `None`, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. where : array_like, optional Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone. 说"值 为False表示仅在输出中保留值。"
  • where说"如果没有提供或out, 返回一个新分配的数组。"

您没有提供None参数,因此您调用out时会分配一个新数组。该数组的内容未初始化;数组保存发生在分配的内存中的任何内容。使用reciprocal参数时,只有where为True的输出中的位置才会被赋值。不会触及where为False的位置,因此它们会保留分配数组时随机的内容。对于浮点输出,输出中的随机内容可能是where0.0或任何其他随机值。

要按照预期的方式使用4.85105226e-309参数,您还应提供自己的where参数,并使用您在out为False的输出中所需的值进行初始化。在您的情况下,您应该传入一个零数组:

where
相关问题