C++ internal representation of double/float

旧时模样 提交于 2019-12-11 18:38:51

问题


I am unable to understand why C++ division behaves the way it does. I have a simple program which divides 1 by 10 (using VS 2003)

double dResult = 0.0;
dResult = 1.0/10.0;

I expect dResult to be 0.1, However i get 0.10000000000000001

  1. Why do i get this value, whats the problem with internal representation of double/float
  2. How can i get the correct value?

Thanks.


回答1:


Because all most modern processors use binary floating-point, which cannot exactly represent 0.1 (there is no way to represent 0.1 as m * 2^e with integer m and e).

If you want to see the "correct value", you can print it out with e.g.:

printf("%.1f\n", dResult);



回答2:


Double and float are not identical to real numbers, it is because there are infinite values for real numbers, but only finite number of bits to represent them in double/float.

You can further read: what every computer scientist should know about floating point arithmetics




回答3:


The ubiquitous IEEE754 floating point format expresses floating point numbers in scientific notation base 2, with a finite mantissa. Since a fraction like 1/5 (and hence 1/10) does not have a presentation with finitely many digits in binary scientific notation, you cannot represent the value 0.1 exactly. More generally, the only values that can be represented exactly are those that fit precisely into binary scientific notation with a mantissa of a few (e.g. 24 or 53 or 64) binary digits, and a suitably small exponent.



来源:https://stackoverflow.com/questions/8656947/c-internal-representation-of-double-float

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