In Java, there are two main types for representing floating-point numbers: float (32 bits) and double (64 bits). float is less precise and takes up less memory, while double provides greater precision and is the preferred default type for floating-point numbers.
Important features:
Example of comparison with delta:
public class DoubleComparison { public static void main(String[] args) { double a = 0.1 + 0.2; double b = 0.3; double epsilon = 1e-10; if (Math.abs(a - b) < epsilon) { System.out.println("Equal considering the precision"); } else { System.out.println("Not equal"); } } }
Question: What will the following code output?
System.out.println(0.1 + 0.2 == 0.3);
Answer: This code will output false, because the result of the sum 0.1 + 0.2 in the IEEE 754 binary format is not exactly equal to 0.3 due to the peculiarities of storing decimal fractions in float and double types.
Story
On a large financial project, money counters used the double type. In practice, small operations often led to accumulated rounding errors, resulting in final sums differing by a few cents. The issue was solved by replacing double with BigDecimal.
Story
In a game engine, a float array was used to store object coordinates in a world with large values. When moving over long distances, the accuracy of object positioning began to degrade, resulting in "trembling" objects on the screen. Replacing float with double and centering the coordinates helped resolve the issue.
Story
In a statistical analysis program, double values were compared using the
==operator and unexpected numbers of "mismatches" were encountered. After switching to delta comparison, the program logic worked correctly.