If I understand correctly, the return value for floor division is always a whole number, even if the dividend and/or divisor are not whole numbers, so why does it not always return an integer.
It's detrimental in my case because converting from a large float to an int instead of having the return value as an arbitrary-precision integer obviously loses precision.
I can't see any function that does float floor division to return an integer. Obviously I could make a function to do so, e.g. by multiplying both values by the same amount so that they're both integers, but it would be a lot slower than a C implementation.
Here's an example: 5.2 // 2
is 2.0
not 2
.
In answer to your question why?, it is by design, and the rationale for this is in 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, sincefloor()
of a complex number is not allowed.
This PEP dates back to Python 2.2. I've suppressed a paragraph that discusses the now obsolete distinction between int
and long
.