python - 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
解决方案
我能够在 numpy repo 上找到这个密切相关的 github 问题。根据numpy
and的主要贡献者Robert Kern 的说法scipy
,关于结果类型的决定是根据输入类型做出的。numpy
依赖于具有特定类型实现的底层例程,其中两个参数属于相同类型,因此它必须提升为某种通用类型。在这种情况下,问题在于一种类型是无符号的,而另一种是有符号的:
...这是几个因素的汇合。作为这些例程基础的
numpy.add()
ufunc 的实现仅具有特定于类型的实现,其中两个参数属于同一类型。因此 ufunc 系统需要将参数转换为通用类型。其中一个参数是有符号的,因此两个参数都需要转换为有符号类型。可以在最大范围内表示值的最小有符号类型uint64
是float64
(注意!并非所有uint64
值都可以表示为浮点数!精度会丢失!但它比值的整个上半部分丢失float64
的地方要好。)。int64
请注意,无符号和有符号 numpy 类型也会发生类似的情况, np.uint
并且np.int
:
>>> import numpy as np
>>> np.uint(0) + np.int64(1)
1.0
推荐阅读
- python - 有没有更快的方法将熊猫数据框分成两个互补的部分?
- javascript - 我们可以比较javascript运行时中的数据类型吗
- swift - 如何在 swift struct/class 类型中支持这种初始化?
- java - 从 Firebase 存储中检索和设置图像?
- python - 把名词改成代词造句
- powershell - 对于 dotnetcore 3.1 Windows 服务如何使用 powershell 脚本 5.1 停止、卸载、安装和启动服务
- ios - 如何在 iOS 中使用自定义 tableview 单元格笔尖,将滑动表视图控制器作为单元格的默认控制器
- c# - 如何反序列化具有相同名称但不同类型的 API 响应
- python - 极小极大的评估函数
- c++ - 如何在链表中搜索特定字符串并返回该值?