Comparing Floating-Point Numbers Safely
You'll learn why checking if two floating-point numbers are exactly equal often fails, and how to compare them correctly using a tolerance value.
The Problem with Direct Equality
Because of the rounding errors you learned about in "Floating-Point Arithmetic and Rounding Errors," two floating-point numbers that should be equal mathematically often aren't exactly equal in Java. When you perform calculations, tiny precision errors accumulate.
For example, if you calculate 0.1 + 0.2, you might expect it to equal 0.3 exactly. But due to how computers store decimal numbers in binary, the result might be 0.30000000000000004 instead. A direct equality check would fail!
The Epsilon Tolerance Solution
Instead of checking if two float or double values are exactly equal, check if they're close enough. You define a small tolerance value called epsilon (often written as a variable) and ask: "Is the difference between these numbers smaller than my tolerance?"
Think of it like archery: you don't need to hit the exact center of the bullseye—hitting within a tiny circle around it counts as success.
double a = 0.1 + 0.2;
double b = 0.3;
double epsilon = 0.0001; // our tolerance
if (Math.abs(a - b) < epsilon) {
System.out.println("Close enough!");
}
The Math.abs(a - b) calculates the absolute difference (distance) between the two numbers. If that distance is smaller than epsilon, you consider them equal for practical purposes.
The right epsilon value depends on your application—financial calculations might need tighter tolerance than physics simulations.
Key Takeaway: Never use == to compare float or double values. Always use an epsilon tolerance and check if the absolute difference is smaller than your acceptable margin of error.