The math.fmod(x, y) function returns the floating-point remainder of x / y as defined by the C standard library. Unlike Python's native modulo operator (%), math.fmod() always carries the exact sign of the dividend (x), making it the preferred function for floating-point calculations, signal processing, and robotics.
IEEE 754 Alternative: To compute the remainder where the quotient is rounded to the nearest integer rather than truncated toward zero, see math.remainder().
The math.fmod() function requires importing the math module and accepts two arguments:
import math
remainder = math.fmod(x, y)
| Parameter | Type | Required? | Description |
|---|---|---|---|
x |
int or float |
Yes | The dividend (the number being divided). The return value always adopts the sign of x. |
y |
int or float |
Yes | The divisor (the number dividing x). Cannot be 0. |
Return Value: Returns a floating-point number (float) representing x - n * y, where n is x / y truncated towards zero.
Basic division with positive integers and floating-point values:
import math
print(math.fmod(10, 2)) # Output: 0.0
print(math.fmod(10, 3)) # Output: 1.0
print(math.fmod(10.5, 4)) # Output: 2.5
0.0
1.0
2.5
Notice that the return value is always a float, even when passing integer arguments.
The most important distinction in Python mathematics is how math.fmod() differs from the built-in % operator when negative numbers are involved:
math.fmod(x, y): Uses truncated division (truncates towards zero). The remainder always carries the sign of x (dividend).x % y: Uses floored division (rounds down towards negative infinity). The remainder always carries the sign of y (divisor).| Expression | math.fmod(x, y) |
x % y |
Explanation |
|---|---|---|---|
x = -10, y = 3 |
-1.0 | 2 | fmod adopts negative sign of x; % rounds down towards $-\infty$ and carries positive sign of y. |
x = 10, y = -3 |
1.0 | -2 | fmod adopts positive sign of x; % carries negative sign of y. |
x = -10, y = -3 |
-1.0 | -1 | Both yield negative values because both operands are negative. |
import math
x, y = -25, 3
print("math.fmod(-25, 3):", math.fmod(x, y)) # Output: -1.0
print("-25 % 3: ", x % y) # Output: 2
% operator when cycling through non-negative array indices or working strictly with integers. Use math.fmod() whenever working with floating-point calculations or porting algorithms from C, C++, Java, or JavaScript.
Due to standard binary floating-point representation (IEEE 754), fractional modulo operations can yield numbers with tiny trailing decimal imprecisions:
import math
res = math.fmod(10.5, 3.2)
print("Raw result:", res) # 0.8999999999999995 instead of exact 0.9
# Best Practice: Use math.isclose() for floating-point comparisons
print("Is close to 0.9?", math.isclose(res, 0.9)) # True
A notable difference between math.fmod() and % is the exception raised when the divisor is zero:
0 as divisor to math.fmod(x, 0) raises a ValueError: math domain error.x % 0 raises a ZeroDivisionError.import math
try:
math.fmod(10, 0)
except ValueError as err:
print("Caught expected domain error:", err)
# Output: Caught expected domain error: math domain error
In robotics, drone navigation, and video games, angles often accumulate beyond full rotations (e.g. $+540^\circ$ or $-750^\circ$). We frequently need to wrap angles into a symmetric span from $-180^\circ$ to $+180^\circ$. Let's build an angle normalizer using math.fmod() verified with unit assertions:
import math
def normalize_heading(angle):
# Wrap angle into range [-180, 180)
wrapped = math.fmod(angle + 180, 360)
if wrapped < 0:
wrapped += 360
return wrapped - 180
# Unit Assertions
assert normalize_heading(0) == 0.0
assert normalize_heading(190) == -170.0
assert normalize_heading(-200) == 160.0
assert normalize_heading(360) == 0.0
assert normalize_heading(725) == 5.0
print("Heading for 190 deg: ", normalize_heading(190))
print("Heading for -200 deg:", normalize_heading(-200))
print("All heading normalizer assertions passed successfully!")
Open in Google Colab View on GitHub
Run all math.fmod() examples interactively, contrast negative sign behaviors with %, and verify the heading normalizer with unit assertions directly in Google Colab.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.