C fmod Function

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
ParameterTypeDescription
xFloating-pointThe dividend. Sign determines the sign of the result
yFloating-pointThe 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 of y's sign.
  • Magnitude constraint: The absolute value of the result is always less than |y|, unless x or y is 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, and long double. Integer operands are implicitly converted.
  • Divisor must be non-zero: Passing 0.0 as y triggers a domain error (EDOM) and returns NaN.
  • Precision limitations: Very large x or very small y can cause catastrophic cancellation, reducing significant digits in the result.
  • No implicit wrapping: Unlike integer %, fmod does not guarantee results within [0, y) for negative inputs.
  • math_errhandling: Controls whether errors are reported via errno, floating-point exceptions, or both. Check MATH_ERRNO and MATH_ERREXCEPT macros for strict compliance.

Best Practices

  1. Always validate divisor: Check y == 0.0 before calling fmod to avoid runtime domain errors.
  2. Use type-specific variants: Prefer fmodf or fmodl when working with float or long double to prevent implicit conversions.
  3. Distinguish from remainder(): Use remainder() when you need IEEE 754 rounding to the nearest integer instead of truncation toward zero.
  4. Handle NaN propagation: Test results with isnan() before using them in control flow or further calculations.
  5. Normalize results manually if needed: For mathematical modulo behavior (always positive), use (fmod(x, y) + y) % y pattern.
  6. Enable strict floating-point handling: Compile with -frounding-math or -fno-fast-math if exact IEEE 754 behavior is critical.

Common Pitfalls

  • 🔴 Confusing with % operator: fmod follows 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 NaN propagation or undefined behavior in strict environments.
  • 🔴 Precision loss in subtraction: When x is vastly larger than y, fmod may return inaccurate remainders due to floating-point cancellation.
  • 🔴 Assuming sign symmetry: fmod(-x, y) and fmod(x, -y) do not produce symmetric results. Sign always follows x.
  • 🔴 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 -lm during compilation. Omission causes linker errors.

Performance and Alternatives

  • Hardware optimization: Modern FPUs provide dedicated instructions for floating-point remainder. fmod typically maps directly to these instructions.
  • remainder(): Alternative that rounds x/y to 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 fmod intrinsics. 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/

Leave a Reply

Your email address will not be published. Required fields are marked *


Macro Nepal Helper