you have to use the absolute difference between the numbers and compare this difference with a number that is below 1 and greater than zero.
Not exactly. Even granting always subtracting the smaller from the larger, with that plan, 1.99
is equal to 1.01
, and 2.49
is equal to 1.51
. Instead, replace the 1
with some chosen epsilon value appropriate for the situation, and take the absolute value of the comparison. 1.0
is almost always too large for the epsilon. Something like 0.000001
might be a better fit, but again: how precise you need to be can depend on the situation.
What is the relation between rounding and equality
Imagine you want to represent 1/3
as a decimal. You can't! The decimal value repeats forever. Instead, you have to settle for recording the value up to some number of digits. Effectively, you have rounded the value. This is the nature of base-10 numbers, and it turns out base-2 (binary) has the same issue. In fact, 0.1
works out the same way with base 2: you can't store it exactly as a double value.
Therefore, many of the values you work with in floating point number spaces (of which IEEE-754 is by far the most common, as there is direct CPU support and optimization) are actually just rounded representations of the actual number, and of course this stretches to equality checking.
Now, an alternative strategy for comparing two doubles is rounding them both to the same number of decimal places, and then comparing whether the rounded values are actually equal, as was shown in the question's code sample. This is not recommended. Thanks to the optimization and the inexact nature of floating numbers just explained, it's possible the rounded values end up as subtly different numbers, and will still not be exactly equal.