Java – Why Addition of Doubles is Not Equal to Their Sum

floating pointjavanumeric precision

I am aware of the floating point errors as I had gained some knowledge with my question asked here in SE Floating Point Errors.

What I am finding it difficult to understand is, the output of the following program.

        double d1 = 0 + 1.123 + 2.456;
        double d2 = 3.579;

        float f1 = 0f + 1.123f + 2.456f;
        float f2 = 3.579f;

        long l1 = (long)(0 + 1.123 + 2.456);
        long l2 = (long)3.579;

        System.out.println(d1==d2);  // Output = false;
        System.out.println(f1==f2);  // Output = true;
        System.out.println(l1==l2);  // Output = true;

Why is the output "false" for double and not for float, even when float is single precision 32 bit and double is double precision 64 bit. Oracle docs

Any help with this would be highly appreciated.

Best Answer

Consider this hypothetical.

You have two data types. One is a floating point number with 32 bits of precision that is base 3 (represented by the digits 0, 1, and 2). The other is a floating point number with 64 bits of precision that is base 4.

Given this code:

float a = .3 + .6
float b = .9;

print(a == b)

The comparison will return true if base 3 floats are used, and false if base 4 floats are used, even though the base 4 float has a much higher precision.

Why is this? Because the numbers 3, 6, and 9 can be represented exactly in the base 3 float, but can only be approximated in the base 4 float, no matter how many digits of precision there are.

This is why floating point numbers should never be compared using ==. They should always be compared using a range of allowable error.

Related Topic