Integer division in Python 3 - strange result with negative number [duplicate] Integer division in Python 3 - strange result with negative number [duplicate] python python

Integer division in Python 3 - strange result with negative number [duplicate]


// is not integer division, but floor division:

7/-3  -> -2.33333...7//-3 -> floor(7/-3) -> floor(-2.33333...) -> -3

PEP 238 on Changing the Division Operator:

The // operator will be available to request floor division unambiguously.

See also Why Python's Integer Division Floors (thanks to @eugene y) - Basically 7//-3 is -7//3, so you want to be able to write:

-7 = 3 * q + r

With q an integer (negative, positive or nul) and r an integer such that 0 <= r < 3. This only works if q = -3:

-7 = 3 * (-3) + 2


// is the operator for floor division.

This means that after the division is completed the "floor" function is applied (the value retrieved from the division is rounded down to the nearest integer regardless of whether the decimal part is greater or less than .5)

As for your example, be careful to note that for negative answers the floor division operator will still be rounding down (e.g. -5/2 --> -2.5 --> -3).