Numpy数组整数/浮点除法 [英] Numpy array integer / float division

查看:37
本文介绍了Numpy数组整数/浮点除法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 Python/NumPy 中的以下行为有些奇怪:

I found the following behaviour in Python/NumPy somewhat strange:

In [51]: a = np.arange(10, 20)
In [52]: a = a / 10.0
In [53]: a
Out[53]: array([ 1. ,  1.1,  1.2,  1.3,  1.4,  1.5,  1.6,  1.7,  1.8,  1.9])

In [54]: a = np.arange(10, 20)
In [55]: a /= 10.0
In [56]: a
Out[56]: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])

我觉得 a=a/10.0a/=10.0 应该返回相同的结果.这是有意并在某处记录的吗?

I felt that a=a/10.0 and a/=10.0 should return the same result. Is this intended and documented somewhere?

推荐答案

a/= 10.0 的问题在于它就地修改了数组,并且不会改变数组,因此所有浮点数都转换为整数.另一方面 a = a/10.0 创建了一个新数组,如果正在创建一个新数组,则可以更改类型.

The problem with a /= 10.0 is that it modifies the array in place, and it won't change the the dtype of the array, so all the floats are converted to integers. On the other hand a = a / 10.0 created a new array, and the type can be changed if a new array is being created.

来自 文档:

请注意,如果分配更高的类型,分配可能会导致更改降低类型(如浮点数到整数)甚至异常(分配复杂到浮点数或整数):

Note that assignments may result in changes if assigning higher types to lower types (like floats to ints) or even exceptions (assigning complex to floats or ints):

这篇关于Numpy数组整数/浮点除法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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