2

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.

9

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.

  • So this would be basically because the decimals are not represented correctly in binary form and when we compare, we basically compare bits? – JNL Jul 18 '13 at 21:31
  • Yes. They're not represented exactly in binary form; they are (almost) always approximations. Further, the internal representation of the 32 bit float is different than that of the 64 bit float. – Robert Harvey Jul 18 '13 at 21:33
  • Beautiful. This definitely comes through experience. Thanks Robert – JNL Jul 18 '13 at 21:42
  • I am not a C# developer, but it seems there's a datatype "decimal" in C#, so that would basically go through the same error? or have they implemented it in a better way to handle such cases? – JNL Jul 18 '13 at 22:37
  • 1
    @JNL: See stackoverflow.com/q/5940222 – Robert Harvey Jul 18 '13 at 22:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.