gpt4 book ai didi

python - numpy.int64 乘以 int -> numpy.float64

转载 作者:太空狗 更新时间:2023-10-29 17:35:08 26 4
gpt4 key购买 nike

我将 python3 与 numpy 版本 1.8.2(与 numpy 1.10.4 和 python2 相同的问题)一起使用,并尝试做一些非常基本的事情:将两个整数相乘。

import numpy as np
a = 9223372036854775808
type(a)
b = np.int64(0)
type(b)
type(b*a)

但是输出是:

builtins.int
numpy.int64
numpy.float64

所以两个整数相乘返回一个 float !有什么合理的解释吗?

请注意,如果我更改为

a = 9223372036854775807
type(b*a)

返回

numpy.int64

如果我把它提高到

a = 92233720368547758100
type(b*a)

返回(在 python3 中)

builtins.int

和(在 python2 中)

long

据我所知肯定有一些溢出,但为什么?

最佳答案

其实是很好的观察和提问。这是一个简单的类比:

import numpy as np

a = 9223372036854775808

请注意,您正在穿越 int极限,它正在进入long int范围

a will produce output as 9223372036854775808L

type(a) will produce output as <type 'long'>

在下面的例子中,我们留在 int 中限制

a = 9223372036854775807

Here a returns output as 9223372036854775807

type(a) returns output as <type 'int'>

让我们假设b = np.int64(1)例如。我会在稍后解释为什么我选择 np.int64(1)而不是 np.int64(0)

b*a returns 9.2233720368547758e+18, as you see it is represented in decimals in Euler's form.

type(b*a) returns np.float64

因此,由于上述原因,它被转换为 float ,即 np.float(64)。欧拉形式的数字总是需要 float /小数点来表示

考虑的原因b作为np.int64(1) : 如果是np.int64(0) ,你永远不会注意到输出,因为结果全是 0

关于python - numpy.int64 乘以 int -> numpy.float64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35928453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com