javadouble-precision

Different values in calculating harmonic sum from left to right and right to left


When calculating harmonic sum of numbers from 1 to 50000 in java in both directions, the values obtained must match but it is blowing my mind that they don't! Kindly tell me why is it happening so.

public class Main {
    public static void main(String args[]){
        int maxD = 50000;
        double suml2r=0, sumr2l=0;
        for(int i=1; i<=maxD; i++){
            suml2r += (double)(1)/i;
            sumr2l += (double)(1)/(maxD-i+1);
        }

        System.out.println("left to right = " + suml2r);
        System.out.println("right to left = " + sumr2l);
    }
}

Output:
left to right = 11.397003949278504
right to left = 11.397003949278519


Solution

  • Floating point is not precise! In the right to left sum you're adding from smallest to largest, and the least significant remnants have a change to accumulate, unlike in the left to right sum where a longer part of the mantissa needs to be dropped for the smallest added numbers. There's a reason why equality check for exact float values is usually a bad idea.