Different results when adding same doubles in different order

floating-accuracy, floating-point, java

Solution

Floating point numbers lose precision as you do more operations. Generally, you get the highest precision by adding the smallest numbers first. (So the result does depend on the order of operations)

In addition to maintaining the same order of operations, you'll also have to use strictfp to get the same result on different platforms.

Or better yet, don't use floating points: use a BigDecimal instead.

Problem

Why is the output different when adding same numbers? ``` public class Test { public static void main(String a[]) { double[] x = new double[]{3.9, 4.3, 3.6, 1.3, 2.6}; System.out.println(">>>>>>> " + sum(x)); } public static double sum(double[] d) { double sum = 0; for (int i = 0; i < d.length; i++) { sum += d[i]; } return sum; } } ``` Output is : `15.7` and if I interchange values ``` double[] x = new double[] {2.6, 3.9, 4.3, 3.6, 1.3}; ``` I am getting Output as : `15.700000000000001` How do I get the same Output ?

Original source