np.mod(a, b) returns the remainder of a divided by b for each pair of elements, and like Python's built-in %, the result always takes the sign of the divisor, b, not the dividend, a — so -7 mod 3 is 2, not -1, since the result's sign follows the positive divisor. This differs from the C/Java-style remainder operator, which instead takes the sign of the dividend, so translating modulo-based code from those languages into NumPy/Python can silently produce different results for negative operands.
1Understanding np.mod()
np.mod(a, b) returns the remainder of a divided by b for each pair of elements, and like Python's built-in %, the result always takes the sign of the divisor, b, not the dividend, a — so -7 mod 3 is 2, not -1, since the result's sign follows the positive divisor. This differs from the C/Java-style remainder operator, which instead takes the sign of the dividend, so translating modulo-based code from those languages into NumPy/Python can silently produce different results for negative operands.
If you're porting an algorithm from C, Java, or JavaScript that relies on the sign of a modulo result, double-check it against Python's floor-division-based convention — negative operands can produce a different sign than you'd get in those other languages.
import numpy as np
a = np.array([10, 11, 12])
b = np.array([3, 3, 3])
print(np.mod(a, b))2Practical Example
Here is a real-world application of np.mod() showing how it is used in production NumPy code.
import numpy as np
print(np.mod(-7, 3))
print(np.fmod(-7, 3))3Best Practices
Follow these guidelines when working with np.mod():
1. Double-check modulo behavior with negative operands specifically when porting code from a language with a different remainder-sign convention
2. Use np.mod() (or %) for wraparound logic like cyclic indexing, since its always-positive-with-positive-divisor result is usually exactly what that needs
3. Use np.fmod() instead of np.mod() specifically when you need C-style, dividend-sign remainder behavior for compatibility with another system
Tip: If you're porting an algorithm from C, Java, or JavaScript that relies on the sign of a modulo result, double-check it against Python's floor-division-based convention — negative operands can produce a different sign than you'd get in those other languages.
import numpy as np
a = np.array([10, 11, 12])
b = np.array([3, 3, 3])
print(np.mod(a, b))