首页 > 解决方案 > strange implicit conversion of data type in numpy

问题描述

I create a simple numpy of data type uint as below:

import numpy as np
a = np.array([1,2,3], dtype=np.uint)

When I compute

a[0] + 1

I expect a result of 2, but it gives

2.0

Why there is such an implicit conversion to float for np.uint? Note that it does not happen with int or np.int64

标签: pythonnumpy

解决方案


我能够在 numpy repo 上找到这个密切相关的 github 问题根据numpyand的主要贡献者Robert Kern 的说法scipy,关于结果类型的决定是根据输入类型做出的。numpy依赖于具有特定类型实现的底层例程,其中两个参数属于相同类型,因此它必须提升为某种通用类型。在这种情况下,问题在于一种类型是无符号的,而另一种是有符号的:

...这是几个因素的汇合。作为这些例程基础的 numpy.add()ufunc 的实现仅具有特定于类型的实现,其中两个参数属于同一类型。因此 ufunc 系统需要将参数转换为通用类型。其中一个参数是有符号的,因此两个参数都需要转换为有符号类型。可以在最大范围内表示值的最小有符号类型uint64float64(注意!并非所有uint64值都可以表示为浮点数!精度会丢失!但它比值的整个上半部分丢失float64的地方要好。)。int64

请注意,无符号和有符号 numpy 类型也会发生类似的情况, np.uint并且np.int

>>> import numpy as np
>>> np.uint(0) + np.int64(1)
1.0

推荐阅读