Comparing floating-point numbers
What you'll learn: Why you should never use the == operator to compare float or double values and how to compare them safely instead.
The problem with precision
In C, integers are exact. If you have five apples, you have exactly 5.000... apples. However, floating-point numbers (float and double) are stored using a binary system that cannot perfectly represent every decimal fraction.
Think of it like trying to write the fraction 1/3 as a decimal. No matter how many 3s you write (0.3333...), you will never truly reach the exact value. Computers face this same struggle with simple numbers like 0.1 or 0.2. Because of these tiny rounding errors, a calculation that "should" result in 0.3 might actually result in 0.30000000000000004. If you ask C if 0.3 == 0.30000000000000004, it will say false.
The "Epsilon" solution
Since floating-point numbers are rarely perfectly equal, we don't ask if they are identical. Instead, we ask if they are "close enough."
We do this by defining a very small threshold called epsilon. If the absolute difference between two numbers is smaller than epsilon, we treat them as equal for the purposes of our program.
Coding the comparison
To compare two floats safely, you subtract one from the other, take the absolute value (using fabs() from the math.h library), and check if the result is less than your tiny threshold.
#include <stdio.h>
#include <math.h> // Required for fabs()
int main() {
double a = 0.1 + 0.2;
double b = 0.3;
double epsilon = 0.00001;
// WRONG: This will likely fail due to precision errors
if (a == b) {
printf("Exactly equal\n");
}
// RIGHT: Check if the difference is negligible
if (fabs(a - b) < epsilon) {
printf("Close enough to be considered equal!\n");
}
return 0;
}
In the example above, a == b would be false because 0.1 + 0.2 results in a value slightly higher than 0.3 deep in the decimal places. By using epsilon, we ignore those microscopic errors.
Key takeaway
Never use == with floats; instead, check if the absolute difference between two values is less than a tiny threshold (epsilon).