Dividing negative numbers with floordiv in python

integer-division, negative-number, python

Solution

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

Problem

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.

Original source

Related problems