Why different result? float vs double [duplicate]

烂漫一生 提交于 2021-02-11 16:50:41

问题


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 and double are different.
  • Therefore the differences (the errors) between decimal and binary floating point representations are liable to be different in float versus double.
  • 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!