Definition
The fmod function computes the floating-point remainder of the division of two numbers. It implements the modulo operation for floating-point types, returning the value x - n * y where n is the quotient of x / y truncated toward zero. It is the floating-point equivalent of the integer % operator but follows IEEE 754 remainder rules.
Syntax and Parameters
#include <math.h> double fmod(double x, double y); float fmodf(float x, float y); // C99 long double fmodl(long double x, long double y); // C99
| Parameter | Type | Description |
|---|---|---|
x | Floating-point | The dividend. Sign determines the sign of the result |
y | Floating-point | The divisor. Must not be zero |
Mathematical Behavior and Sign Rules
- Truncation toward zero:
n = trunc(x / y), not floor. This differs from mathematical modulo which uses floor division. - Sign inheritance: The result always carries the same sign as
x(the dividend), regardless ofy's sign. - Magnitude constraint: The absolute value of the result is always less than
|y|, unlessxoryis infinite/NaN. - IEEE 754 compliance: Precisely defined behavior for edge cases including infinities, zeros, and NaN values.
Code Examples
#include <stdio.h>
#include <math.h>
#include <errno.h>
int main(void) {
// Basic remainder
printf("fmod(10.5, 3.2) = %.4f\n", fmod(10.5, 3.2)); // 0.9000
// Sign follows dividend (x), not divisor (y)
printf("fmod(-10.0, 3.0) = %.1f\n", fmod(-10.0, 3.0)); // -1.0
printf("fmod(10.0, -3.0) = %.1f\n", fmod(10.0, -3.0)); // 1.0
// Division by zero handling
errno = 0;
double result = fmod(5.0, 0.0);
if (errno == EDOM || isnan(result)) {
printf("Domain error: division by zero\n");
}
return 0;
}
Rules and Constraints
- Floating-point only: Designed exclusively for
float,double, andlong double. Integer operands are implicitly converted. - Divisor must be non-zero: Passing
0.0asytriggers a domain error (EDOM) and returnsNaN. - Precision limitations: Very large
xor very smallycan cause catastrophic cancellation, reducing significant digits in the result. - No implicit wrapping: Unlike integer
%,fmoddoes not guarantee results within[0, y)for negative inputs. math_errhandling: Controls whether errors are reported viaerrno, floating-point exceptions, or both. CheckMATH_ERRNOandMATH_ERREXCEPTmacros for strict compliance.
Best Practices
- Always validate divisor: Check
y == 0.0before callingfmodto avoid runtime domain errors. - Use type-specific variants: Prefer
fmodforfmodlwhen working withfloatorlong doubleto prevent implicit conversions. - Distinguish from
remainder(): Useremainder()when you need IEEE 754 rounding to the nearest integer instead of truncation toward zero. - Handle NaN propagation: Test results with
isnan()before using them in control flow or further calculations. - Normalize results manually if needed: For mathematical modulo behavior (always positive), use
(fmod(x, y) + y) % ypattern. - Enable strict floating-point handling: Compile with
-frounding-mathor-fno-fast-mathif exact IEEE 754 behavior is critical.
Common Pitfalls
- 🔴 Confusing with
%operator:fmodfollows truncation semantics, not floor semantics. Results for negative numbers differ from mathematical modulo expectations. - 🔴 Ignoring domain errors: Failing to check for zero divisor causes silent
NaNpropagation or undefined behavior in strict environments. - 🔴 Precision loss in subtraction: When
xis vastly larger thany,fmodmay return inaccurate remainders due to floating-point cancellation. - 🔴 Assuming sign symmetry:
fmod(-x, y)andfmod(x, -y)do not produce symmetric results. Sign always followsx. - 🔴 Using for loop counters: Floating-point modulo is unsuitable for integer-style iteration. Rounding errors accumulate and break termination conditions.
- 🔴 Missing math library: POSIX systems require
-lmduring compilation. Omission causes linker errors.
Performance and Alternatives
- Hardware optimization: Modern FPUs provide dedicated instructions for floating-point remainder.
fmodtypically maps directly to these instructions. remainder(): Alternative that roundsx/yto the nearest integer instead of truncating. Often slower but mathematically cleaner for certain algorithms.- Integer
%: Use for whole-number arithmetic. Faster, deterministic, and avoids floating-point precision issues. - Manual implementation: For specific rounding behaviors or embedded systems without FPU support, custom truncation logic may be necessary but sacrifices performance.
- Vectorization: SIMD libraries (AVX, NEON) provide parallel
fmodintrinsics. Use for batch processing of large floating-point arrays.
Linking Requirements
On POSIX-compliant systems (Linux, macOS, Unix), mathematical functions reside in a separate library. Compile with:
gcc main.c -lm -o main
Windows MSVC and modern toolchains often link math functions automatically, but explicit -lm remains required for cross-platform portability and strict standard compliance.
Advanced C Functions & String Handling Guides (Parameters, Returns, Reference, Calls)
https://macronepal.com/c/understanding-pass-by-reference-in-c-pointers-semantics-and-safe-practices/
Explains pass-by-reference in C using pointers, allowing functions to modify original variables and manage memory efficiently.
https://macronepal.com/aws/c-function-arguments/
Explains function arguments in C, including how values are passed to functions and how arguments interact with parameters.
https://macronepal.com/aws/understanding-pass-by-value-in-c-mechanics-implications-and-best-practices/
Explains pass-by-value in C, where copies of variables are passed to functions without changing the original data.
https://macronepal.com/aws/understanding-void-functions-in-c-syntax-patterns-and-best-practices/
Explains void functions in C that perform operations without returning values, commonly used for tasks like printing output.
https://macronepal.com/aws/c-return-values-mechanics-types-and-best-practices/
Explains return values in C, including different return types and how functions send results back to the calling function.
https://macronepal.com/aws/understanding-function-calls-in-c-syntax-mechanics-and-best-practices/
Explains how function calls work in C, including execution flow and parameter handling during program execution.
https://macronepal.com/c/mastering-functions-in-c-a-complete-guide/
Provides a complete overview of functions in C, covering structure, syntax, modular programming, and real-world usage examples.
https://macronepal.com/aws/c-function-parameters/
Explains function parameters in C, focusing on defining inputs for functions and matching them with arguments during calls.
https://macronepal.com/aws/c-function-declarations-syntax-rules-and-best-practices/
Explains function declarations in C, including prototypes, syntax rules, and best practices for organizing programs.
https://macronepal.com/aws/c-strstr-function/
Explains the strstr() string function in C, used to locate substrings within a string and perform text-search operations.
Online C Code Compiler
https://macronepal.com/free-online-c-code-compiler-2/