Course contentsShow
← C
Lesson 907 of 1,21912. The Standard LibraryFree lesson

Precision and epsilon in `float.h`

Precision and epsilon in float.h

What you'll learn: How to use the FLT_EPSILON constant to handle the tiny rounding errors inherent in floating-point math.

The problem with "Equal"

In the world of C, floating-point numbers (float and double) are not perfectly precise. They are approximations. Because computers represent numbers in binary, some simple decimals—like 0.1—cannot be stored exactly. They end up as something like 0.10000000149.

If you perform a few calculations and then check if two floats are exactly equal using ==, your program might fail even if the math looks correct on paper. This is where the <float.h> header becomes essential.

Meet the Epsilon

The float.h header defines a constant called FLT_EPSILON. Think of Epsilon as the smallest possible difference the computer can recognize between 1.0 and the next highest representable number.

In plain English: Epsilon is the "margin of error." Instead of asking "Are these two numbers identical?", we ask "Is the difference between these two numbers so small that it’s negligible?"

Using Epsilon in code

To use this, we check if the absolute difference between two numbers is less than FLT_EPSILON.

#include <stdio.h>
#include <float.h>
#include <math.h> // for fabsf (absolute value of a float)

int main() {
    float a = 0.1f + 0.2f;
    float b = 0.3f;

    // Direct comparison is risky! 
    // a might be 0.30000001
    if (fabsf(a - b) < FLT_EPSILON) {
        printf("The numbers are close enough to be considered equal.\n");
    } else {
        printf("The numbers are significantly different.\n");
    }

    return 0;
}

Why this matters

When you are building systems that rely on precision—like a physics engine for a game or a financial calculator—relying on == with floats will eventually cause a bug that is incredibly hard to track down. By using the limits defined in float.h, you acknowledge that floating-point math is "fuzzy" and give your program a specific threshold for what counts as "close enough."

Key takeaway

Use FLT_EPSILON from <float.h> to compare floats by checking if their difference is smaller than the machine's limit of precision.