If I test the following code, i get some strange results. I know there's a problem with doubles, since 2.1 is not 2.1 in IEEE-754. But shouldn't these be all equally wrong? The first three give 4.2, the last one 4.200000000000001
public static void main(String[] args)
{
double[] arr1 = {0.2, 0.2, 0.2, 0.5, 0.5, 0.5, 2.1};
double[] arr2 = {0.5, 0.5, 0.5, 0.2, 0.2, 0.2, 2.1};
double[] arr3 = {2.1, 0.5, 0.5, 0.5, 0.2, 0.2, 0.2};
double[] arr4 = {2.1, 0.2, 0.2, 0.2, 0.5, 0.5, 0.5};
System.out.println(sumarray(arr1, 0, arr1.length-1));
System.out.println(sumarray(arr2, 0, arr2.length-1));
System.out.println(sumarray(arr3, 0, arr3.length-1));
System.out.println(sumarray(arr4, 0, arr4.length-1));
}
public static double sumarray(double[] arr, int p, int r) {
double sum=arr[p];
for (int k=p+1; k<=r; k++) {
sum = sum + arr[k];
}
return sum;
}