numpy 数组,a /= x 与 a = a / x 之间的区别

numpy array, difference between a /= x vs. a = a / x

我正在使用 python 2.7.3,当我执行以下代码时:

import numpy as np

a = np.array([[1,2,3],[4,5,6]])
a = a / float(2**16 - 1)
print a

这将导致以下输出:

>> array([[1.52590219e-05, 3.05180438e-05, 4.57770657e-05],
>>       [6.10360876e-05, 7.62951095e-05, 9.15541314e-05]])

完全符合预期,但是当我执行以下代码时:

import numpy as np

a = np.array([[1,2,3],[4,5,6]])
a /= float(2**16 - 1)
print a

我得到以下输出:

>> array([[0, 0, 0],
>>        [0, 0, 0]])

我期望输出与上一个示例相同,但我不明白不同的输出,这似乎是使用 a /= float(2**16 - 1)a = a / float(2**16 - 1).

的结果

From the documentation:

Warning:

In place operations will perform the calculation using the precision decided by the data type of the two operands, but will silently downcast the result (if necessary) so it can fit back into the array. Therefore, for mixed precision calculations, A {op}= B can be different than A = A {op} B. For example, suppose a = ones((3,3)). Then, a += 3j is different than a = a + 3j: while they both perform the same computation, a += 3 casts the result to fit back in a, whereas a = a + 3j re-binds the name a to the result.

由于您的数组是一个整数数组,当使用就地操作时,结果将再次向下转换为整数。

如果您更改数组以使其最初存储浮点数,则结果(浮点数)可以存储在原始数组中,并且您的代码可以正常工作:

>>> a = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
>>> a /= float(2**16 - 1)
>>> a
array([[  1.52590219e-05,   3.05180438e-05,   4.57770657e-05],
       [  6.10360876e-05,   7.62951095e-05,   9.15541314e-05]])