4

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.

Kevin Lee
  • 89
  • 1
  • 6

1 Answers1

10

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
scanny
  • 26,423
  • 5
  • 54
  • 80
  • Python's `Decimal` package is odd in this sense though, it behaves more like `trunc` and removes the decimal (so it behaves the same for positive numbers, but the negative numbers merely – AER Jul 25 '23 at 16:50