问题
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?
回答1:
Why are the results different?
In a general sense:
- Because the binary representations for
float
anddouble
are different. - Therefore the differences (the errors) between decimal and binary floating point representations are liable to be different in
float
versusdouble
. - When the representation errors are different for the respective numbers, the errors after calculation are liable to be different.
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.floatToRawBits
method and its double
analog. 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.
来源:https://stackoverflow.com/questions/60462330/why-different-result-float-vs-double