浮点数的小数精度 [英] Decimal precision of floats
问题描述
相当于 log10(2^24) ≈ 7.225 个十进制数字
equivalent to log10(2^24) ≈ 7.225 decimal digits
精度:7位
6
std::numeric_limits<float>::digits10
为什么 numeric_limits 在这里返回 6?Wikipedia 和 MSDN 都报告说浮点数具有 7 位十进制数字的精度.
Why numeric_limits return 6 here? Both Wikipedia and MSDN report that floats have 7 decimal digits of precision.
推荐答案
如果有疑问,请阅读规范.C++ 标准说 digits10
是:
If in doubt, read the spec. The C++ standard says that digits10
is:
无需更改即可表示的以 10 为基数的位数.
Number of base 10 digits that can be represented without change.
这有点模糊;幸运的是,有一个脚注:
That's a little vague; fortunately, there's a footnote:
相当于FLT_DIG、DBL_DIG、LDBL_DIG
Equivalent to FLT_DIG, DBL_DIG, LDBL_DIG
这些是在 C 标准中定义的;让我们看看那里:
Those are defined in the C standard; let's look it up there:
小数位数,q,这样任何具有 q 个小数位的浮点数都可以四舍五入为具有 p 基数 b 位的浮点数,然后再次返回而无需更改为 q 个小数位.
number of decimal digits, q, such that any floating-point number with q decimal digits can be rounded into a floating-point number with p radix b digits and back again without change to the q decimal digits.
所以 std::numeric_limits<float>::digits10
是十进制位数,因此如果将其转换为 float,任何具有这么多位数的浮点数都不会改变
并返回十进制.
So std::numeric_limits<float>::digits10
is the number of decimal digits such that any floating-point number with that many digits is unchanged if you convert it to a float
and back to decimal.
正如您所说,浮点数具有大约 7 位的小数精度,但固定宽度小数和浮点数的表示误差并不是统一的对数.将 1.xxx.. 形式的数字四舍五入到固定小数位数的相对误差比将 9.xxx.. 四舍五入到相同位数的相对误差几乎十倍小数位.同样,根据值在二进制中的位置,将其四舍五入为 24 位二进制数字的相对误差可能会相差近两倍.
As you say, floats have about 7 digits of decimal precision, but the error in representation of both fixed-width decimals and floats is not uniformly logarithmic. The relative error in rounding a number of the form 1.xxx.. to a fixed number of decimal places is nearly ten times larger than the relative error of rounding 9.xxx.. to the same number of decimal places. Similarly, depending on where a value falls in a binade, the relative error in rounding it to 24 binary digits can vary by a factor of nearly two.
这样做的结果是,并非所有七位小数都能在往返浮动和返回的往返过程中幸存下来,但所有六位小数都可以.因此,std::numeric_limits
为 6.
The upshot of this is that not all seven-digit decimals survive the round trip to float and back, but all six digit decimals do. Hence, std::numeric_limits<float>::digits10
is 6.
对于 float
类型,在有效范围内具有指数的六位和七位小数并不多;如果您仍然不相信,您可以很容易地编写一个程序来详尽地测试所有这些.
There are not that many six and seven digit decimals with exponents in a valid range for the float
type; you can pretty easily write a program to exhaustively test all of them if you're still not convinced.
这篇关于浮点数的小数精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!