gpt4 book ai didi

python - 2.5//2.0 在 Python 3.x 中返回 float 而不是 int 背后的基本原理是什么?

转载 作者:行者123 更新时间:2023-11-28 21:07:15 25 4
gpt4 key购买 nike

2.5//2.0 在 Python 3.x 中返回 float 而不是 int 背后的基本原理是什么?如果它是一个整数值,为什么不把它放在一个 int 类型的对象中呢?

[编辑]

我正在寻找事实的理由。这样做的论据是什么。还没有找到他们。

[编辑2]

floor 的关系比术语“floor division”所暗示的更成问题!

floor(3.5/5.5) == 0 (int)

鉴于

3.5//5.5 == 0.0( float )

这里还不能辨别任何逻辑:(

[编辑3]

来自 PEP238:

In a unified model, the integer 1 should be indistinguishable from the floating point number 1.0 (except for its inexactness), and both should behave the same in all numeric contexts.

一切都很好,但像 Numpy 这样并非不重要的库在提供 float 作为索引时会提示,即使它们是不可或缺的。所以“无法区分”还不是现实。花了一些时间寻找与此相关的错误。得知 // 的真正本质后,我感到非常惊讶。从文档中(对我而言)并不是那么明显。

因为我对 Python 3.x 的设计相当信任,所以我想我一定错过了一个非常明显的理由来以这种方式定义 //。但是现在我想知道...

最佳答案

// 运算符包含在 PEP 238 中.首先,请注意它不是“整数除法”而是“底数除法”,即从未声称结果将是整数。

摘自关于楼层划分语义的部分:

Floor division will be implemented in all the Python numeric types, and will have the semantics of

a // b == floor(a/b)

except that the result type will be the common type into which a and b are coerced before the operation.

之后:

For floating point inputs, the result is a float. For example:

3.5//2.0 == 1.0

这个决定背后的理由没有明确说明(或者我找不到)。但是,它的实现方式与其他数学运算(强调我的)是一致的:

Specifically, if a and b are of the same type, a//b will be of that type too. If the inputs are of different types, they are first coerced to a common type using the same rules used for all other arithmetic operators.

此外,如果结果自动转换为 int,对于超出整数精度的非常大的 float ,可能会产生奇怪且令人惊讶的结果:

>>> 1e30 // 2.
5e+29
>>> int(1e30 // 2.)
500000000000000009942312419328

关于python - 2.5//2.0 在 Python 3.x 中返回 float 而不是 int 背后的基本原理是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41703269/

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