python - 为什么 Numpy 对待 a+=b 和 a=a+b 的方式不同

标签 python numpy

以下 numpy 行为是故意的还是错误?

from numpy import *

a = arange(5)
a = a+2.3
print 'a = ', a
# Output: a = 2.3, 3.3, 4.3, 5.3, 6.3 

a = arange(5)
a += 2.3
print 'a = ', a
# Output: a = 2, 3, 4, 5, 6

Python 版本:2.7.2,Numpy 版本:1.6.1

最佳答案

这是故意的。

+= 运算符保留数组的类型。换句话说,整数数组仍然是整数数组。

这使 NumPy 能够使用现有的数组存储执行 += 操作。另一方面,a=a+b 为 sum 创建一个全新的数组,并重新绑定(bind) a 以指向这个新数组;这会增加用于操作的存储量。

引用 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 首先是一个整数数组,请考虑以下几点:

In [3]: np.arange(5).dtype
Out[3]: dtype('int64')

In [4]: np.arange(5.0).dtype
Out[4]: dtype('float64')

关于python - 为什么 Numpy 对待 a+=b 和 a=a+b 的方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10739978/

相关文章:

arrays - 在numpy中创建具有不同维度的数组数组

python - np.mean() 的值错误?

python - 由不同数据帧的唯一值组成的新数据帧

python - 检测 python 程序是否通过 Windows GUI(双击)与命令提示符执行

python-3.x - Numpy:递归生成矩阵

python - 如何在 Python 中以空格和逗号分隔?

python - 如何更新二维 numpy 数组?

python - NumPy:将一维数组转换并 reshape 为带有零的二维数组?

python - 一次在数据框列上应用多个函数

python - Django unicode 连接