Part 1: How Java's double Represents Numbers
This is Part 1 of Floating Point Without Tears, a series about working with numbers in Java.
Adding up a list of numbers seems straightforward. We can use a loop, a stream, or a parallel stream, and expect the same total from each.
With double, the way we group the additions can affect that total. The type has limited precision, so some intermediate results have to be rounded. If we change which additions happen first, we can change where rounding happens and end up with a different answer.
Before looking at streams, let's see this with just three numbers. Both expressions below add two ones to the same large value:
double value = 1e16;
System.out.println((value + 1.0) + 1.0);
System.out.println(value + (1.0 + 1.0));
The output is:
1.0E16
1.0000000000000002E16
1e16 means 10,000,000,000,000,000. The first calculation returns that same number. The second returns a number two larger. In ordinary arithmetic, both expressions would give the second answer.
The difference comes from which numbers a double can store and when Java rounds the result of an addition.
A Java double uses the 64-bit format defined by IEEE 754. That gives it a finite set of possible values. Some numbers fit exactly, including 0.5, 1.0 and the 1e16 used here. Other numbers fall between the available values and have to be rounded.1
At 1e16, the next larger double is 10,000,000,000,000,002. There is no double for 10,000,000,000,000,001. We can check the size of this gap with Math.ulp:
System.out.println(Math.ulp(value)); // 2.0
ulp stands for "unit in the last place." For this positive value, it tells us the distance to the next larger double. The spacing is much smaller around 1.0. As numbers move into larger ranges, the gaps grow.2
Adding 1.0 to 1e16 puts the exact answer halfway between two available values. Java has a fixed rule for these ties, called "round to nearest, ties to even." Here, that rule chooses 1e16. The "even" refers to the binary representation, not the last decimal digit.3
That explains the first expression. The first addition rounds back to 1e16. The second addition does the same. Neither 1.0 survives in the result.
In the second expression, Java adds 1.0 + 1.0 first. The result is exactly 2.0. Adding that to 1e16 gives a value that double can store exactly.
The mathematical rule that lets us regroup additions without changing their result is called associativity. Floating-point addition does not always follow it. Each addition can require rounding, so changing the grouping can change the answer.3
This matters when we sum a collection:
import java.util.List;
List<Double> values = List.of(1e16, 1.0, 1.0);
double sequential = values.stream().reduce(0.0, Double::sum);
double parallel = values.parallelStream().reduce(0.0, Double::sum);
System.out.println(sequential);
System.out.println(parallel);
A parallel reduction can split the values into groups, sum each group, and combine the results. That can change which additions happen first. If the two small values are added together before they meet the large value, they can survive in the total.
The Stream.reduce contract requires an associative operation. Floating-point addition does not meet that requirement in general, so these calls are an illustration of the problem: we cannot rely on the sequential and parallel results being identical. They may happen to match for a particular input and implementation.4
For summing double values, Java also provides DoubleStream.sum(). Its implementation may use compensated summation, which keeps track of some of the rounding error to improve the total. This means it can produce a different result from reduce(0.0, Double::sum). Its API still leaves the order of additions unspecified, so it does not guarantee the same result under every grouping.5
Large numbers are only one way to encounter rounding. It can also happen when a decimal value is first stored as a double. In binary, 0.1 is a repeating fraction, much as one third repeats in decimal. A double has to stop after a limited number of binary digits, so it stores a nearby value.6
This is why another familiar example behaves as it does:
System.out.println(0.1 + 0.2); // 0.30000000000000004
System.out.println(0.1 + 0.2 == 0.3); // false
The addition produces a different stored value from the one used for 0.3. The comparison correctly reports that difference. When the question is whether two calculated values are close enough, we need to define an acceptable error for the calculation. A tolerance copied from another program may be too strict or too loose for ours.
For prices and balances that require exact decimal values, I would start with BigDecimal and decimal input such as new BigDecimal("0.10"). We still need to decide when and how to round, especially for division. Converting a result to BigDecimal after information has already been lost in double arithmetic cannot recover that information.6
For measurements or statistics, double may provide all the precision the application needs. The questions to settle are how much error is acceptable and whether the calculation must produce exactly the same result each time. A fixed calculation order helps with repeatability, but it can still repeat an inaccurate result.
Before replacing a loop with a parallel stream, I would test values of different magnitudes and check the result against those requirements. Our opening example needs only three values to show why that check matters.
Next: Part 2: Associativity, Identity, and Folding.
-
Java Language Specification, section 4.2.3: Floating-Point Types and Values. ↩
-
Java Language Specification, section 15.4: Floating-point Expressions and section 15.18.2: Additive Operators for Numeric Types. ↩ ↩2
-
BigDecimal API documentation, including the notes on decimal inputs, the double constructor, and rounding. ↩ ↩2