为什么当除数 and/or 被除数是浮点数时 Python 下限除法 return 是浮点数?

Why does Python floor division return a float when the divisor and/or dividend is a float?

如果我没理解错的话,floor除法的return值总是整数,即使被除数and/or除数不是整数,为什么不总是[=25] =] 一个整数。

这对我来说是不利的,因为从大浮点数转换为 int 而不是将 return 值作为任意精度整数显然会失去精度。

我看不到任何将浮点除法除以 return 整数的函数。显然我可以创建一个函数来这样做,例如通过将两个值乘以相同的量使它们都是整数,但它会比 C 实现慢很多。

这是一个例子:5.2 // 22.0 而不是 2

在回答您的问题 为什么? 时,这是设计使然,其基本原理在 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.

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.

...

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.

此 PEP 可追溯到 Python 2.2。我删除了一段讨论 intlong.

之间现已过时的区别的段落