Course contentsShow
← C
Lesson 104 of 1,2192. Variables and TypesFree lesson

Comparing floats for equality

Comparing floats for equality

What you'll learn: Why you should never use == to compare floating-point numbers and how to compare them safely using a tiny margin of error.

The "Close Enough" problem

Imagine you are measuring a wooden plank. One ruler says it is 100 centimeters long. A laser measurer says it is 100.0000001 centimeters. To a human, these are the same. To a computer, they are strictly different.

In C, float and double types work like this. Because computers represent decimals using binary (base 2), they often cannot store a number like 0.1 perfectly. Instead, they store a value like 0.10000000149. If you perform calculations, these tiny rounding errors add up. If you try to ask if (0.1 + 0.2 == 0.3), the computer will likely tell you false because the tiny microscopic "dust" at the end of the numbers doesn't match perfectly.

Using an Epsilon

To compare floats correctly, we don't ask "Are they equal?" Instead, we ask "Is the difference between them so small that it doesn't matter?"

We call this small threshold an Epsilon. If the absolute difference between two numbers is less than Epsilon, we treat them as equal.

Safe comparison in code

To do this, we use the fabs() function (which stands for "floating-point absolute value") from the <math.h> library. This turns a negative difference into a positive one, so it doesn't matter which number is larger.

#include <stdio.h>
#include <math.h>
#include <stdbool.h>

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

    // Define a tiny margin of error
    double epsilon = 0.00001;

    // BAD: This will likely fail
    if (a == b) {
        printf("They are equal!\n");
    }

    // GOOD: Check if the difference is smaller than epsilon
    if (fabs(a - b) < epsilon) {
        printf("They are close enough to be considered equal.\n");
    }

    return 0;
}

By using this method, you protect your program from "invisible" math errors that occur deep inside the computer’s processor. Whether you are building a physics engine or a financial tool, always give your floats a little room to breathe.

Key takeaway

Never use == with floats; instead, check if the absolute difference between two numbers is less than a tiny threshold (Epsilon).