Recently I was solving an interesting bug that came down to comparing two Double
variables with equals
method. It looks innocent, what can be wrong with something like firstDouble.equals(secondDouble)
?
The problem here is with how doubles are stored. To fit them into 64bytes (usually) they are rounded.
See the example below:
Double firstDouble = 0d;
for (int i = 1; i <= 42; i++) {
firstDouble += 0.1;
}
Double secondDouble = 0.1 * 42;
System.out.println(firstDouble); // 4.200000000000001
System.out.println(secondDouble); // 4.2
System.out.println(firstDouble.equals(secondDouble)); // false
This inaccuracy is caused by rounding errors.
We need to use a different approach to compare those doubles.
#java #double comparison in java #double comparison #comparisons #double