math.fmod(x, y) returns the floating-point remainder x - n * y for integer n = trunc(x / y), so the result keeps the sign of x (the dividend).
This matches C's fmod() and differs from Python's % operator, which floors the quotient and keeps the sign of y (the divisor): math.fmod(-7, 3) is -1.0 whereas -7 % 3 is 2.
math.fmod() is a function in Python's standard math module: import it with import math and call math.fmod(...), or import the name directly with from math import fmod.
Syntax
Import math and pass dividend x and nonzero divisor y.
python
import math
rem = math.fmod(x, y)
Call
What it does
math.fmod(-7, 3)
Returns -1.0 (sign matches dividend -7).
math.fmod(7, -3)
Returns 1.0 (sign matches dividend 7).
math.fmod(5.0, float("inf"))
Returns 5.0.
math.fmod(5.0, 0.0)
Raises ValueError: divisor cannot be zero.
For exact integer arithmetic, prefer Python's % operator; for IEEE nearest-even remainder centered around zero, use math.remainder().
Function signatures
python
math.fmod(x, y, /)
# returns: float x - trunc(x / y) * y (exact in binary64)
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
Exact floating-point remainder with the same sign as x and |rem| < |y|.
Python Examples
Example 1 — Contrast math.fmod() With Python's % Operator on Negatives
Observe how fmod() keeps the dividend sign while % keeps the divisor sign.
python
import math
for x, y in [(-7, 3), (7, -3), (-7.5, 2.5)]:
rem = math.fmod(x, y)
print(f"({x}, {y}) -> fmod={rem} %={x % y}")
Exact multiple preserves -0.0. Dividing -7.5 by 2.5 leaves -0.0 in fmod and 0.0 in %.
Example 2 — Wrap Signed Rotation Offsets Symmetrically Around Zero
Keep signed clockwise and counterclockwise rotations inside (-360, 360).
python
import math
for deg in [-400.0, -190.0, 380.0]:
wrapped = math.fmod(deg, 360.0)
print(f"{deg:>6.1f} -> {wrapped:>6.1f}")
Output
-400.0 -> -40.0
-190.0 -> -190.0
380.0 -> 20.0
How It Works
Preserves rotation direction. A negative rotation of -400.0 wraps to -40.0 rather than jumping to +320.0.
In-range angles unchanged.-190.0 stays -190.0 because its magnitude is below 360.0.
Positive excess wraps normally.380.0 drops full circle to 20.0.
Example 3 — Handle Zero Divisors and Infinite Dividends Safely
Check finite dividends divided by inf and catch ValueError on invalid calls.
python
import math
print(math.fmod(5.0, float("inf")))
for a, b in [(5.0, 0.0), (float("inf"), 2.0)]:
try:
math.fmod(a, b)
except ValueError:
print(f"fmod({a}, {b}) raises ValueError")
math.fmod() keeps the sign of the dividend x (matching C fmod), while % floors toward -inf and keeps the sign of the divisor y. Also math.fmod() always returns a float.
For floats, fmod() avoids rounding errors that can leave x % y slightly larger than y or subtly imprecise, and preserves sign of x cleanly.