numpy 中数据类型的奇怪隐式转换

kst*_*stn 7 python numpy

我创建了一个简单的 numpy 数据类型 uint ,如下所示:

import numpy as np
a = np.array([1,2,3], dtype=np.uint)
Run Code Online (Sandbox Code Playgroud)

当我计算时

a[0] + 1
Run Code Online (Sandbox Code Playgroud)

我期望结果为 2,但它给出了

2.0
Run Code Online (Sandbox Code Playgroud)

为什么 np.uint 需要隐式转换为 float?请注意,int 或 np.int64 不会发生这种情况

jua*_*aga 1

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

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

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

>>> import numpy as np
>>> np.uint(0) + np.int64(1)
1.0
Run Code Online (Sandbox Code Playgroud)