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:

    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:

    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.