math.remainder(x, y) returns the IEEE 754 remainderx - n * y, where n is the integer closest to x / y.
If x / y lies exactly halfway between two integers, n is rounded to the even integer—so math.remainder(8, 3) returns -1.0 and math.remainder(3.0, 2.0) returns -1.0. The result always stays within [-|y|/2, +|y|/2].
math.remainder() is a function in Python's standard math module: import it with import math and call math.remainder(...), or import the name directly with from math import remainder. Added in Python 3.7.
Syntax
Import math and pass dividend x and nonzero divisor y.
python
import math
delta = math.remainder(x, y)
Call
What it does
math.remainder(7, 3)
Returns 1.0 (nearest multiple is 6 = 2 * 3).
math.remainder(8, 3)
Returns -1.0 (nearest multiple is 9 = 3 * 3).
math.remainder(3.0, 2.0)
Returns -1.0 (1.5 ties to even 2).
math.remainder(5.0, 0.0)
Raises ValueError: divisor cannot be zero.
Added in Python 3.7. Unlike math.fmod() or %, remainder() can be negative even when both inputs are positive.
Function signatures
python
math.remainder(x, y, /)
# added in Python 3.7; exact IEEE 754 x - round_even(x / y) * y
Parameters
Parameter
Description
x
Required positional finite dividend (int or float).
y
Required positional nonzero divisor (int or float).
Return Value
Return Value
Description
float
Signed distance from x to the nearest integer multiple of y.
Python Examples
Example 1 — Find Signed Offsets to the Nearest Grid Step
Measure how far numbers sit from the nearest multiple of 3.0 using math.remainder().
python
import math
for pos in [2.2, 7.0, 8.0, 10.6]:
offset = math.remainder(pos, 3.0)
nearest = pos - offset
print(f"{pos:>4.1f} -> offset={offset:+5.1f} nearest={nearest:>4.1f}")