Python math.fmod(): Float Modulo vs. % Operator

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().

Syntax & Parameters 🔝

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 Examples 🔝

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
Expected Output
0.0
1.0
2.5

Notice that the return value is always a float, even when passing integer arguments.

fmod() vs. % Operator: Negative Number Sign Rules 🔝

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
When to use which? Use Python's native % 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.

Floating-Point Precision & math.isclose() 🔝

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

Zero Division & ValueError Handling 🔝

A notable difference between math.fmod() and % is the exception raised when the divisor is zero:

  • Passing 0 as divisor to math.fmod(x, 0) raises a ValueError: math domain error.
  • In contrast, evaluating 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

Hands-on Exercise: Symmetric Angle Normalizer with Assertions 🔝

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:

Python Exercise: Navigation Heading Normalizer
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!")

Practice in Google Colab & GitHub 🔝

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.




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer