What issues arise when comparing doubles?
Issues arise when comparing doubles because of how they are stored in memory. For instance, 1.1 can be represented as 1.0999999999999999 or 1.1. When comparing these two values with ‘==’, they will not be equal, even if they are supposed to be the same number.
Why are there sometimes issues with doubles?
Issues arise because of how Java stores floating point values in memory. Java uses a binary representation of these numbers, and it is not always possible to store real number values with total precision in binary. Doubles are designed to be fast, not necessarily accurate. A good explanation of this is found here:
What are good ways to compare doubles?
One way to compare doubles is to use a threshold. With the example in the first question, if there were a threshold for error of 0.0001, then the difference between 1.0999999999999999 and 1.1 would be less than the threshold. Another way to compare doubles is rounding. However, the more calculations, the greater the possibility that there will be larger rounding errors. Rounding is not always guaranteed to work. A third way to compare doubles is to use Java’s BigDecimal class to define floating point numbers.