Search code examples
javacomputer-scienceprecision

Why different result? float vs double


System.out.println(0.1F + 0.2F); // 0.3
System.out.println(0.1D + 0.2D); // 0.30000000000000004

I understood 0.1D + 0.2D ~= 0.30000000000000004.
But I guessed these result are same, but it is not.
Why result are different?


Solution

  • Why are the results different?

    In a general sense:

    • Because the binary representations for float and double are different.
    • Because neither float or double binary representations have a precise representation for 0.3.
    • Therefore the differences (the errors) between the closest decimal and binary floating point representations for 0.3 are different in float versus double.

    Errors can creep in and/or compound when converting the decimal numbers to binary, when doing the arithmetic, and when converting the binary back to decimal to print out the number. They are inherent / unavoidable to all computations involving Real numbers and finite numeric representations on a practical computer.

    For a broader treatment, read: Is floating point math broken?


    Now if you were so inclined, you could examine the binary representations for the numbers here, and work out precisely where the errors are occurring here:

    • in the decimal -> binary floating point conversion
    • in the floating point arithmetic
    • in the binary floating point conversion -> decimal conversion,
    • or in more than one of the above.

    If you really want to dig into it, I suggest that you take a look at Float.floatToRawIntBits method and its double precision analog Double.doubleToRawLongBits. These will allow you to examine the binary floating point representations. You can then manually convert them to exact real numbers and work out the errors compared with the "ideal" decimal representations.

    It is tedious.