How does the % modulo operator work with positive and negative numbers in Python? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How does the % modulo operator work with positive and negative numbers in Python?

message-square
0

In Python, the % modulo operator uses floored division (a == (a // b) * b + (a % b) where a // b rounds toward $-\infty$), which guarantees that the remainder a % b always carries the same sign as the divisor b (or equals 0) and satisfies $0 \le a \bmod b < b$ for $b > 0$ and $b < a \bmod b \le 0$ for $b < 0$—unlike C, C++, Java, and JavaScript, which use truncated division toward zero.

Basic Example

# 1. Positive dividend and positive divisor:
print(7 % 3)     # Output:  1   (7 == 2 * 3 + 1)

# 2. Negative dividend, positive divisor -> result is NON-NEGATIVE (sign of divisor +3):
print(-7 % 3)    # Output:  2   (-7 == -3 * 3 + 2, because -7 // 3 == -3)

# 3. Positive dividend, negative divisor -> result is NON-POSITIVE (sign of divisor -3):
print(7 % -3)    # Output: -2   (7 == -3 * -3 + (-2), because 7 // -3 == -3)

# 4. Negative dividend, negative divisor -> result is NON-POSITIVE (sign of divisor -3):
print(-7 % -3)   # Output: -1   (-7 == 2 * -3 + (-1), because -7 // -3 == 2)

# 5. Practical payoff: cyclic indexing & clock arithmetic work seamlessly with negative offsets!
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
print(days[-1 % 7])  # Output: 'Sun' (-1 % 7 == 6, wraps cleanly without special cases)

Key Details & Edge Cases

  • The Fundamental Division Identity (divmod):
    • Python strictly enforces the invariant a == (a // b) * b + (a % b) for all numeric types (int and float) when b != 0. Because // performs floor division ($\lfloor a / b \rfloor$), -7 // 3 evaluates to -3 (not -2), forcing -7 % 3 to equal -7 - (-3 * 3) = 2.
    • Calling q, r = divmod(a, b) computes (a // b, a % b) together in a single operation.
  • When you actually need C/Java-style truncated remainder (sign of the dividend a):
    • If you are porting C, Java, or JavaScript algorithms (such as hash functions or low-level bit/codec specs) that expect -7 % 3 == -1, use math.fmod(a, b) (note: math.fmod always returns a float) or for exact arbitrary-precision integers write a - int(a / b) * b / decimal.Decimal(a) % decimal.Decimal(b).
  • Floating-point % precision and math.remainder() (IEEE 754):
    • Floating-point modulo (-0.1 % 0.3 $\rightarrow$ 0.2) follows the same floored sign rule as integers, though binary floating-point representation can introduce tiny rounding artifacts (e.g., 1.0 % 0.1 $\rightarrow$ 0.09999999999999995).
    • Python’s math.remainder(x, y) implements IEEE 754 round-to-nearest-even remainder, returning values in $[-|y|/2, +|y|/2]$.
  • Zero divisor always raises ZeroDivisionError:
    • Evaluating x % 0 or x % 0.0 raises ZeroDivisionError: integer modulo by zero (or float modulo).
  • Checking odd/even integers safely (n % 2 == 1 vs. n % 2 != 0):
    • Because -3 % 2 == 1 in Python (unlike C/Java where -3 % 2 == -1), both n % 2 == 1 and n % 2 != 0 work reliably for negative odd integers in Python—though n % 2 != 0 (or n & 1) remains the clearest cross-language idiom.

Comparison of Remainder / Modulo Functions in Python

Operation 7, 3 -7, 3 7, -3 -7, -3 Sign of Non-Zero Result Return Type Best Used When
a % b (Floored Modulo) 1 2 -2 -1 Same as divisor b int (if both int) or float Cyclic wrap-around indexing ((i - step) % n), clock/angle math, and standard Python integer arithmetic.
divmod(a, b) (2, 1) (-3, 2) (-3, -2) (2, -1) Same as divisor b (q, r) tuple Unit conversions (seconds $\rightarrow$ (minutes, seconds)), pagination, and base conversion in one step.
math.fmod(a, b) (Truncated) 1.0 -1.0 1.0 -1.0 Same as dividend a Always float Porting C/C++/Java/JavaScript remainder logic where sign matches the dividend.
math.remainder(a, b) (IEEE 754) 1.0 -1.0 1.0 -1.0 Closest to 0 ($\in [- b /2,