Skip to content
Advertisement

Unexpected integer division vs. floating-point division result in Python

Running the following code in Python produces a somewhat unexpected result.

print(10000 // 0.1)  # prints 99999.0
print(10000 / 0.1)  # prints 100000.0

Now, I might have understood the discrepancy if both results were the same, because of how floating point numbers are stored in binary. The question is why is the second result different from the first one? Is there a difference in how / and // work besides the latter “flooring” the result?

Advertisement

Answer

// computes the floor of the exact result of the division. / computes the nearest representable float to the exact result of the division.

For dividend 10000 (exactly 10000) and divisor 0.1 (slightly higher than the real number 0.1 due to floating-point limitations), the exact result is very slightly lower than 100000, but the difference is slight enough that the nearest representable float is 100000.0.

// produces 99999.0 because the exact result is less than 100000, but / produces 100000.0 rather than something like 99999.99999999999 because 100000.0 is the closest float to the exact result.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement