Number of significant digits for a floating point type

匆匆过客 提交于 2019-11-26 20:43:01

问题


The description for type float in C mentions that the number of significant digits is 6. However,

float f = 12345.6;

and then printing it using printf() does not print 12345.6, it prints 12345.599609. So what does "6 significant digits" (or "15 in case of a double") mean for a floating point type?


回答1:


According to the standard, not all decimal number can be stored exactly in memory. Depending on the size of the representation, the error can get to a certain maximum. For float this is 0.0001% (6 significant digits = 10^-6 = 10^-4 %).

In your case the error is (12345.6 - 12345.599609) / 12345.6 = 3.16e-08 far lower than the maximum error for floats.




回答2:


6 significant digits means that the maximum error is approximately +/- 0.0001%. The single float value actually has about 7.2 digits of precision (source). This means that the error is about +/- 12345.6/10^7 = 0.00123456. Which is on the order of your error (0.000391).




回答3:


What you're seeing is not really any issue with significant digits, but the fact that numbers on a computer are stored in binary, and there is no finite binary representation for 3/5 (= 0.6). 3/5 in binary looks like 0.100110011001..., with the "1001" pattern repeating forever. This sequence is equivalent to 0.599999... repeating. You're actually getting to three decimal places to the right of the decimal point before any error related to precision kicks in.

This is similar to how there is no finite base-10 representation of 1/3; we have 0.3333 repeating forever.




回答4:


The problem here is that you cannot assure a number can be stored in a float. You need to represent this number with mantissa, base and exponent as IEEE 754 explains. The number printf(...) shows you is the real float number that was stored. You can not assure a number of significant digits in a float number.



来源:https://stackoverflow.com/questions/12815179/number-of-significant-digits-for-a-floating-point-type

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