numpy数组,a/=x与a=a/x之差

2024-04-18 15:52:59 发布

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

在执行以下代码时,我使用的是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

这将产生以下输出:

^{pr2}$

正如预期的那样,但是当我执行以下代码时:

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)vsa = a / float(2**16 - 1)的结果。在


Tags: 代码importnumpy示例asnpfloatarray
1条回答
网友
1楼 · 发布于 2024-04-18 15:52:59

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.

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

如果您更改数组以使其最初存储float,那么结果(即float)可以存储在原始数组中,您的代码将正常工作:

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

相关问题 更多 >