Python floor division: negative numbers and modulo
Learn why -7 // 3 is -3 in Python, how modulo gets its sign, why int(a / b) can lose precision, and how to wrap list indices with negative positions.
Your calculation works for positive numbers, then a negative input shifts the result by one. Python integer division rounds in a specific direction: down the number line.
In short
For Python integers, a // b rounds the quotient toward negative infinity: -7 // 3 is -3, while int(-7 / 3) is -2. The remainder a % b satisfies a == b * (a // b) + a % b and has the divisor's sign unless it is zero. Use divmod(a, b) to get both quotient and remainder. The divisor must be nonzero.
How do /, // and int(a / b) differ?
For two integers, / produces a float and // produces an integer. Converting a float with int() removes its fractional part, moving toward zero. The results agree for small positive quotients; a negative quotient with a fractional part reveals the difference.
print(7 / 3)print(7 // 3)print(-7 // 3)print(int(-7 / 3))print(7.0 // 3)try: print(7 // 0)except ZeroDivisionError as error: print(type(error).__name__ + ":", error)$ python3 operators.py2.33333333333333352-3-22.0ZeroDivisionError: integer division or modulo by zeroThe mathematical quotient of -7 and 3 lies between -3 and -2. Its floor is -3, the greatest integer less than or equal to that quotient. Truncation toward zero gives -2.
Watch the type: 7.0 // 3 produces the float 2.0. Using // does not guarantee an int result for every operand type. The rest of this article uses ordinary Python integers only.
Why is -7 % 3 equal to 2?
The quotient and remainder must reconstruct the original number. With q = -3, you get 3 * (-3) = -9; adding 2 reaches -7.
- 3 * q-9q = -3
- +1-8
- +2-7reached a, r = 2
For a positive divisor, the remainder is at least zero and less than the divisor. For a negative divisor, it is negative or zero. This program covers all four sign combinations, followed by an exact division.
for a, b in [(7, 3), (-7, 3), (7, -3), (-7, -3), (-6, 3)]: q, r = divmod(a, b) print(a, b, q, r, a == b * q + r)$ python3 signs.py7 3 2 1 True-7 3 -3 2 True7 -3 -3 -2 True-7 -3 2 -1 True-6 3 -2 0 TrueEach line contains a, b, the quotient, the remainder, and the identity check. So 7 % -3 is -2. A remainder is not always positive: its sign follows b.
Why avoid int(a / b) for exact integer division?
Using / introduces a float before the conversion. For large integers, that float may already have lost a unit. Converting it back cannot recover the information.
n = 2 ** 53 + 1print(n)print(n // 1)print(int(n / 1))$ python3 precision.py900719925474099390071992547409939007199254740992With this environment's binary floats, 2 ** 53 + 1 does not survive the floating-point division. Keep // when you need the exact floor of an integer quotient.
If your contract requires truncation toward zero, divide the positive magnitudes and restore the sign. This function stays in integer arithmetic; a zero divisor still raises an exception.
def trunc_div(a, b): magnitude_a = -a if a < 0 else a magnitude_b = -b if b < 0 else b q = magnitude_a // magnitude_b return -q if (a < 0) != (b < 0) else q
for a, b in [(-7, 3), (7, -3), (-7, -3), (2 ** 53 + 1, 1)]: print(a, b, trunc_div(a, b))$ python3 truncate.py-7 3 -27 -3 -2-7 -3 29007199254740993 1 9007199254740993Do not replace every division with this function: it implements a different rounding choice. Decide which result your calculation needs first.
How can modulo wrap a list index?
For a nonempty list of length n, position % n stays between 0 and n - 1, even when position is negative. It converts an arbitrary position into a valid index.
values = [5, 6, 7]for position in range(-2, 5): index = position % len(values) print(position, index, values[index])print(values)$ python3 cycle.py-2 1 6-1 2 70 0 51 1 62 2 73 0 54 1 6[5, 6, 7]Position -1 selects the last item; 3 wraps to the first. A position too negative for direct indexing, such as -100, can also be brought into bounds with modulo.
Handle an empty list before calculating the remainder: its length is zero. In the exercise below, the contract requires a new empty list in that case. It also requires preserving the input and handling several laps. Modulo provides the index; you build the result.
take_cyclic
Implement take_cyclic(values, start, count): accept a negative start, wrap after the last item, and leave values unchanged.
For another use of remainders, list filtering uses % 2 to identify even values. If a result changes your input unexpectedly, check the list copying rules.
Frequently asked questions
Does // round to the nearest integer?
No. It takes the floor. For integers, 8 // 3 is 2 even though the quotient is closer to 3.
Is modulo always positive?
No. For Python integers, a nonzero remainder has the divisor's sign. A positive list length therefore gives a nonnegative remainder.
What happens with a zero divisor?
The /, // and % operators and divmod raise ZeroDivisionError for integers. Handle an empty input before using its length as a divisor.
Does this rule apply to every numeric type?
This article covers ordinary int values. Floats introduce rounding, and a type such as Decimal may use different rules. Check the contract of the type you use.
Sources
