I'm confused by the nature of integer division with // or floordiv with negative numbers in python.
>>> -5 // 2
-3
>>> int(-5/2)
-2
Why would floordiv() round down to -3? I thought integer division was supposed to simply drop (or lack) the information after the decimal point.
In arithmetic, the floor function is defined as the largest integer not greater than the operand. Since the largest integer not greater than -2.5 is -3, the results you are seeing are the expected results.
I suppose a way of thinking about it is that floordiv always rounds down (toward the left on the numberline), but acts on the actual value of the operand (-2.5), not its absolute value (2.5).
Wikipedia has more here at Floor and ceiling functions.
Note that the behavior you describe is provided by the math.trunc() function in the Python standard library.
>>> from math import trunc
>>> trunc(-2.5)
-2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With