为什么Numpy对待a + = b和a = a + b的区别 [英] Why Numpy treats a+=b and a=a+b differently

查看:121
本文介绍了为什么Numpy对待a + = b和a = a + b的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is the following numpy behavior intentional or is it a bug?

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

Python version: 2.7.2, Numpy version: 1.6.1

推荐答案

这是故意的.

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

The += operator preserves the type of the array. In other words, an array of integers remains an array of integers.

这使NumPy可以使用现有的阵列存储执行+=操作.另一方面,a=a+b为总和创建一个全新的数组,然后重新绑定a指向该新数组;这会增加用于该操作的存储量.

This enables NumPy to perform the += operation using existing array storage. On the other hand, a=a+b creates a brand new array for the sum, and rebinds a to point to this new array; this increases the amount of storage used for the operation.

引用文档:

警告::就地操作将使用由两个操作数的数据类型决定的精度执行计算,但是会静默向下转换结果(如有必要),以便可以放回到数组中.因此,对于混合精度计算,A {op}= B可能不同于A = A {op} B.例如,假设a = ones((3,3)).然后,a += 3ja = a + 3j不同:虽然它们都执行相同的计算,但是a += 3强制转换结果以适合a,而a = a + 3j将名称a重新绑定到结果.

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首先是整数数组,请考虑以下事项:

Finally, if you're wondering why a was an integer array in the first place, consider the following:

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

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

这篇关于为什么Numpy对待a + = b和a = a + b的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆