简体   繁体   English

浮点类型的有效位数

[英]Number of significant digits for a floating point type

The description for type float in C mentions that the number of significant digits is 6 . C中类型float的描述提到有效位数是6 However, 然而,

float f = 12345.6;

and then printing it using printf() does not print 12345.6 , it prints 12345.599609 . 然后使用printf()打印它不打印12345.6 ,它打印12345.599609 So what does "6 significant digits" (or "15 in case of a double ") mean for a floating point type? 那么对于浮点类型,“6位有效数字”(或“ double情况下为15”)意味着什么呢?

6 significant digits means that the maximum error is approximately +/- 0.0001%. 6位有效数字表示最大误差约为+/- 0.0001%。 The single float value actually has about 7.2 digits of precision ( source ). 单个浮点值实际上具有大约7.2位精度( )。 This means that the error is about +/- 12345.6/10^7 = 0.00123456. 这意味着误差约为+/- 12345.6 / 10 ^ 7 = 0.00123456。 Which is on the order of your error (0.000391). 这是你的错误的顺序(0.000391)。

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 % ). 对于float这是0.0001% (6位有效数字= 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. 在您的情况下,错误是(12345.6 - 12345.599609) / 12345.6 = 3.16e-08远低于浮动的最大错误。

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(= 0.6)没有有限的二进制表示。 3/5 in binary looks like 0.100110011001..., with the "1001" pattern repeating forever. 二进制3/5看起来像0.100110011001 ...,“1001”模式永远重复。 This sequence is equivalent to 0.599999... repeating. 这个序列相当于0.599999 ......重复。 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; 这类似于没有有限的基数-10表示1/3; we have 0.3333 repeating forever. 我们有0.3333永远重复。

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. 您需要用IEEE 754解释的尾数,基数和指数来表示此数字。 The number printf(...) shows you is the real float number that was stored. printf(...)表示您是存储的实数浮点数。 You can not assure a number of significant digits in a float number. 您无法确保浮点数中的多个有效数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM