java - Why does DoubleStream.sum()'s result differ from straight addition? -


i confused. if calculate

system.out.println(0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1); 

then result of 0.9999999999999999. if calculate

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); 

then result of 1.0. why there difference?

the javadoc of double java.util.stream.doublestream.sum() answers question:

in particular, method may implemented using compensated summation or other technique reduce error bound in numerical sum compared simple summation of double values.

in other words, implementation of sum() doesn't have use simple summation of double values (which can have accuracy issues, noticed in first snippet), , therefore may return more accurate result.

edit: note though using doublestream's sum() appears give more accurate result, implementation detail, it's not guaranteed javadoc. besides, simple double addition more efficient, since doesn't have overhead of constructing doublestream. have decide if prefer potential better accuracy or performance.


Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -