浮点比较的问题 [英] problems in floating point comparison
问题描述
void main()
{
float f = 0.98;
if(f <= 0.98)
printf("hi");
else
printf("hello");
getch();
}
我使用的F I我得到不同的结果,不同的浮点数得到这个问题here.On。
为什么会这样?
I am getting this problem here.On using different floating point values of f i am getting different results. Why this is happening?
推荐答案
˚F
使用浮动
precision,但是0.98是双击
默认precision,这样的声明 F&LT; = 0.98
比较使用双击
precision。
f
is using float
precision, but 0.98 is in double
precision by default, so the statement f <= 0.98
is compared using double
precision.
的˚F
因此在比较转换为双击
,但可能使结果比0.98略大
The f
is therefore converted to a double
in the comparison, but may make the result slightly larger than 0.98.
使用
if(f <= 0.98f)
或使用双击
为˚F
代替。
在细节......假设浮动
IEEE单precision 和双击
是的 IEEE双precision 。
In detail... assuming float
is IEEE single-precision and double
is IEEE double-precision.
这些类型的浮点数的存储与基地-2再presentation。在基-2-这个数需要一个无限precision重新present,因为它是一个重复的小数
These kinds of floating point numbers are stored with base-2 representation. In base-2 this number needs an infinite precision to represent as it is a repeated decimal:
0.98 = 0.1111101011100001010001111010111000010100011110101110000101000...
A 浮动
只能存储显著人物24位,即
A float
can only store 24 bits of significant figures, i.e.
0.111110101110000101000111_101...
^ round off here
= 0.111110101110000101001000
= 16441672 / 2^24
= 0.98000001907...
A 双击
可存储signficant人物53位,因此
A double
can store 53 bits of signficant figures, so
0.11111010111000010100011110101110000101000111101011100_00101000...
^ round off here
= 0.11111010111000010100011110101110000101000111101011100
= 8827055269646172 / 2^53
= 0.97999999999999998224...
所以,0.98将成为浮动
在稍大,小双
。
这篇关于浮点比较的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!