Javadoc double java.util.stream.DoubleStream.sum () answers your question:
In particular, this method can be implemented using compensated summation or another method to reduce the error in the numerical sum compared to a simple summation of double values.
In other words, the implementation of sum() does not require a simple summation of double values ββ(which may have problems with accuracy, as you noted in your first fragment), and therefore can return a more accurate result .
EDIT: note that while using the DoubleStream sum() seems to give a more accurate result, this is an implementation detail, so it is not guaranteed by Javadoc. In addition, simply adding a double more efficient since it does not have the overhead of building a DoubleStream . You must decide whether you prefer the potential better accuracy or performance.
source share