Python numpy uint64 在除法时转换为 float

标签 python numpy type-conversion python-2.x

我想做一个简单的整数除法,例如1/3=0,但是 uint64 的行为非常奇怪,导致我的结果被转换为 float 。为什么?

python> uint64(100)/3
Out[0]: 33.333333333333336
python> uint64(100)/uint64(3)
Out[1]: 33
python> int64(100)/3
Out[2]: 33
python> int64(100)/uint64(3)
Out[3]: 33.333333333333336
python> int32(100)/int64(3)
Out[4]: 33

最佳答案

这是因为 Python 看到有符号和无符号类型,并尝试自动推导结果类型,该结果类型将被签名。但由于第一个 64 位数字未签名,因此签名版本将需要 65 位。由于Python/Numpy中没有高于64位的整数类型,Python选择float64。除数 3 的标准类型是 int64,这就是为什么第一个示例将转换为 float64。 当然,这也适用于乘法:

python> import numpy as np
python> type( np.int64( 10 ) * np.int64( 1 ) )
Out[0]: numpy.int64
python> type( np.uint64( 10 ) * np.uint64( 1 ) )
Out[1]: numpy.uint64
python> type( np.uint64( 10 ) * np.int64( 1 ) )
Out[2]: numpy.float64

请注意,这种自动类型推导仅适用于不同的有符号类型,因为它与值无关,否则几乎所有类型都必须以 float64 结束,因为例如经过三次连续乘法后,它可能不再适合 uint64

type(uint64(12345678900)*uint64(12345678900))
/usr/bin/ipython:1: RuntimeWarning: overflow encountered in ulong_scalars
#! /usr/bin/python
Out[3]: numpy.uint64

注意:请注意,在 Python 3 中,简单斜杠不再默认为整数除法。相反,您必须使用 3//2 来获取 1 作为 Python 3 中的 3/2 == 1.5

关于Python numpy uint64 在除法时转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36993422/

相关文章:

c# - 使用 Entity Framework 将字符串转换为 DateTime

python - 如何一次更改多个子图的颜色?

python - 来自MinEnclosingCircle和OpenCV(Python)的怪异中心

python - 通过 http 连接到免费的 pythonanywhere 实例

python - py2app/Tkinter应用程序错误: "classic environment is no longer supported"

c++ - 如何将模板参数与 "if"和 "switch"语句一起使用?

python - 在 Mac 上使用 Docker 使用 Py2exe

python - 计算每一行的大写字母

python - OSError : Failed to interpret my file as a pickle (numpy)

php - 无法将类型 'NSTaggedPointerString' 的值转换为 'NSNumber' - 从 PHP 到 Swift