我很困惑。如果我计算
System.out.println(0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1);
然后我得到 0.9999999999999999
的结果。但是如果我计算
Double sum = DoubleStream.builder().add(0.1).add(0.1).add(0.1).add(0.1).add(0.1).add(0.1).add(0.1).add(0.1).add(0.1).add(0.1).build().sum();
System.out.println(sum);
然后我得到 1.0
的结果。
为什么会有差异?
最佳答案
的 Javadoc double java.util.stream.DoubleStream.sum() 回答你的问题:
In particular, this method may be implemented using compensated summation or other technique to reduce the error bound in the numerical sum compared to a simple summation of double values.
换句话说,sum()
的实现不必使用简单的 double 值求和(这可能有准确性问题,正如您在第一个片段中注意到的那样),因此可能返回 more accurate result .
编辑:请注意,即使使用 DoubleStream
的 sum()
似乎给出了更准确的结果,但这是一个实现细节,因此不能由Javadoc。此外,简单的 double
添加效率更高,因为它没有构造 DoubleStream
的开销。您必须决定是否更喜欢潜在的更好的准确性或性能。
关于java - 为什么 DoubleStream.sum() 的结果与直接加法不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46154710/