花车的小数精度 [英] Decimal precision of floats

查看:179
本文介绍了花车的小数精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


相当于log10(2 ^ 24)≈7.225个十进制数字

Wikipedia $ b


精度:7位数字

MSDN
$ b


6

/ blockquote>

  std :: numeric_limits< float> :: digits10 

为什么numeric_limits在这里返回6?维基百科和MSDN都报告浮点数有7个十进制数字的精度。

C ++标准说 digits10 是:


代表没有改变。


这有些模糊;幸运的是,有一个脚注:


相当于FLT_DIG,DBL_DIG,LDBL_DIG

这些在C标准中定义;让我们来看看它:


十进制数字的个数q,这样任何带有十进制数字的浮点数都可以四舍五入到一个带有p基数b位数的浮点数,然后再返回而不改变为q个十进制数。

所以 std :: numeric_limits< float> :: digits10 是十进制数字的位数,如果将其转换为浮点数并返回十进制。



正如你所说,浮点数有十位数的小数精度,但是在表示两个固定宽度小数和浮点数不是一致的对数。将1.xxx格式的数字四舍五入到固定的小数位数的相对误差几乎是舍入9.xxx的相对误差的十倍大。小数位。同样,根据价值在汇率中的位置,将其四舍五入为二进制数字的相对误差可以相差近两倍。



这个结果是不是所有的七位小数在浮动和返回的往返中都存在,但是所有的六位小数都是。因此, std :: numeric_limits< float> :: digits10 是6.



指数在 float 类型的有效范围内的七位小数;你可以很容易地编写一个程序,以彻底测试所有这些,如果你还没有确信。


equivalent to log10(2^24) ≈ 7.225 decimal digits

Wikipedia

Precision: 7 digits

MSDN

6

std::numeric_limits<float>::digits10

Why numeric_limits return 6 here? Both Wikipedia and MSDN report that floats have 7 decimal digits of precision.

解决方案

If in doubt, read the spec. The C++ standard says that digits10 is:

Number of base 10 digits that can be represented without change.

That's a little vague; fortunately, there's a footnote:

Equivalent to FLT_DIG, DBL_DIG, LDBL_DIG

Those are defined in the C standard; let's look it up there:

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.

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.

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.

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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆