单精度不保证6位数字? [英] Aren't 6 digits guarantee in single precision?

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

问题描述

以下是代码

  typedef std :: numeric_limits< float> FL; 

int main()
{
std :: cout.precision(100);

float f1 = 9999978e3;
std :: cout<< f1< (9999978e3十进制数字存储为二进制)<<的std :: ENDL;

float f2 = 9999979e3;
std :: cout<< f2< (9999979e3十进制数字存储为二进制)<<的std :: ENDL;

float f3 = 9999990e3;
std :: cout<< f3< (9999990e3十进制数字存储为二进制)<<的std :: ENDL;

std :: cout<< ----- ^<<的std :: ENDL;



$ b $ p
$ b



  9999978496(9999978e3以二进制形式存储的十进制数)
9999978496(9999979e3以二进制形式存储的十进制数)
9999989760(9999990e3以二进制形式存储的十进制数)
----- ^

存储为二进制的十进制数字保持第六位 9999978e3 9999979e3 (即 7 ),但是 9999990e3 8 而不是 9

保证前6位数字?



是的,如果我回合了,我得到了 9 ,但那不一样;这只会视觉上起作用/有意义。

稍后(在处理数字上),当我将数值应用于该值时,它将在 xxxxx8 8 9760),而不是 xxxxx9 。 +1在这个幅度。

解决方案

不以你认为的方式保证,没有。



通过提供一个反例,对于IEEE754单精度浮点数,最接近的数字是

  9999990000 



  9999989760 

保证是 数字和浮动,当两者均被舍入为六位有效数字时,将是相同的。这是您的平台上 FLT_DIG 的值,假设它实现了IEEE754。例如。最接近浮动数字至 9999979000 9999978496 p>

请参阅 http://www.exploringbinary .com /浮点转换器/


Here's the code:

typedef std::numeric_limits<float> fl;

int main()
{   
    std::cout.precision(100);    

    float f1 = 9999978e3;
    std::cout << f1 << " (9999978e3 decimal number stored as binary)" << std::endl;

    float f2 = 9999979e3;
    std::cout << f2 << " (9999979e3 decimal number stored as binary)" << std::endl;

    float f3 = 9999990e3;
    std::cout << f3 << " (9999990e3 decimal number stored as binary)" << std::endl;

    std::cout << "-----^" << std::endl;
}

which prints:

9999978496 (9999978e3 decimal number stored as binary)
9999978496 (9999979e3 decimal number stored as binary)
9999989760 (9999990e3 decimal number stored as binary)
-----^ 

The decimal numbers stored as binary correctly keep the 6th digit for 9999978e3 and 9999979e3 (which is 7), but the 6th digit of 9999990e3 is 8 and not 9.

Shouldn't floating point precision always guarantee the first 6 digits?

Yes, if I round 89 I got 9, but that's not the same; this will work/make sense only "visually".

Later (on processing numbers), when I'll apply math on that value, it'll work on a xxxxx8 number (9999989760), and not on a xxxxx9. +1 at that magnitude.

解决方案

Not in the way you think it's guaranteed, no.

By way of offering a counter-example, for an IEEE754 single precision floating point, the closest number to

9999990000

is

9999989760

What is guaranteed is that your number and the float, when both are rounded to six significant figures, will be the same. This is be the value of FLT_DIG on your platform, assuming it implements IEEE754. E.g. the closest float number to 9999979000 is 9999978496.

See http://www.exploringbinary.com/floating-point-converter/

这篇关于单精度不保证6位数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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