Precision loss and rounding errors
What you'll learn: Why computers sometimes struggle to store decimal numbers exactly and how to handle the resulting tiny math errors.
The infinite problem
Imagine trying to write down the fraction 1/3 as a decimal. You start with 0.3, then 0.33, then 0.333... but you can never finish because the 3s go on forever. Computers face a similar problem with float and double types.
Computers use a system called binary (base-2) to store data. While humans use base-10, some numbers that look "clean" to us, like 0.1, are actually repeating infinite fractions in binary. Because your computer's memory is finite, it eventually has to "chop off" the end of the number. This is called precision loss.
The "pennies in the jar" analogy
Think of floating-point math like a massive jar where you store millions of pennies. If you add or remove one penny, it’s easy to track. But if you start dealing with "partial" pennies and rounding every transaction to the nearest cent, after a million transactions, you might find you are off by a few dollars.
In C, these tiny errors accumulate. If you add 0.1 to a variable ten times, you might expect exactly 1.0, but the computer might give you 0.999999.
Seeing it in code
If you compare a float directly to a number using ==, your program might fail because of a microscopic difference.
#include <stdio.h>
int main() {
float total = 0.0f;
// Add 0.1 to total ten times
for (int i = 0; i < 10; i++) {
total += 0.1f;
}
// You expect 1.0, but let's see what happens
printf("Total is: %.10f\n", total);
if (total == 1.0f) {
printf("It is exactly 1.0\n");
} else {
printf("It is NOT exactly 1.0!\n");
}
return 0;
}
When you run this, total will likely be something like 1.0000001192. The comparison fails because the computer’s version of 0.1 was just a tiny bit off from the start.
How to handle it
Because of these rounding errors, you should almost never use == to compare two floating-point numbers. Instead, programmers check if the numbers are "close enough" by seeing if the difference between them is a very small range (often called an epsilon).
Key takeaway
Floating-point numbers are approximations, not exact values; always expect tiny rounding errors in your calculations.