gpt4 book ai didi

python 3 层划分并不总是导致 int

转载 作者:太空宇宙 更新时间:2023-11-04 09:04:25 24 4
gpt4 key购买 nike

当在 python3 中使用 floor division 时(可能还有带有 import __future__ 的 python2):

>>> 2//2
1

输出是预期的整数。但是只要一个操作数是 float ,结果就是 float

>>> 2.0//2.0
1.0
>>> 2.0//2
1.0
>>> 2//2.0
1.0

我猜这是故意的,但其实我不明白,为什么要这样。由于始终产生整数的操作而使用先前未确定的数据类型的设计概念是什么?

真正广泛的搜索给了我最好的(来自 PEP 238)

Semantics of Floor Division

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.

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.

In particular:

- if a and b are both ints or longs, the result has the same type and value as
for classic division on these types (including the case of mixed input types;
`int//long` and `long//int` will both return a long).
- For floating point inputs, the result is a float.
For example: `3.5//2.0 == 1.0`
- For complex numbers, // raises an exception, since floor() of a complex number is not allowed.
- For user-defined classes and extension types, all semantics are up to the implementation of the class or type.

但这仍然不能解释为什么行为是这样实现的。

最佳答案

一个可能的优势如下:如果操作的输入是float,那么通常最有用的输出类型是float,因为程序是进行浮点计算。同样,如果操作的输入是整数(intlong),那么通常最有用的输出类型是整数。

一个相关的令人惊讶的数据点:

>>> str(int(123e300 // 10.0))
'12300000000000000348405169443457756499452463917650245579212965288916278422109198944984236481408634018703901759913201583616648277756338685989513894763895354330869046350917957229381143786183918719192956157930593465276658607709014541611368487360619735051905095032755082564499801643679232993692080863707136'

这很令人惊讶,因为很自然地期望结尾处有很多 0。由于 float 类型的精度有限,您会得到其他数字。

因此,通过返回一个float// 表示输出可能不准确。

关于python 3 层划分并不总是导致 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22209232/

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