浮点比较中的问题 [英] problems in floating point comparison

查看:17
本文介绍了浮点比较中的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void main()
{
    float f = 0.98;
    if(f <= 0.98)
        printf("hi");
    else
        printf("hello");
    getch();
}

我在这里遇到了这个问题.在使用 f 的不同浮点值时,我得到了不同的结果.为什么会这样?

I am getting this problem here.On using different floating point values of f i am getting different results. Why this is happening?

推荐答案

f 使用 float 精度,但 0.98 使用 double 精度默认情况下,语句 f <= 0.98 使用 double 精度进行比较.

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 因此在比较中转换为 double,但可能会使结果略大于 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)

或者使用 double 代替 f.

详细...假设 floatIEEE 单精度doubleIEEE 双精度.

In detail... assuming float is IEEE single-precision and double is IEEE double-precision.

这些类型的浮点数以 base-2 表示形式存储.在 base-2 中,这个数字需要无限精度来表示,因为它是一个重复的小数:

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...

一个float只能存储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...

一个double可以存储53位有效数字,所以

A double can store 53 bits of signficant figures, so

       0.11111010111000010100011110101110000101000111101011100_00101000...
                                                              ^ round off here
   =   0.11111010111000010100011110101110000101000111101011100

   =   8827055269646172 / 2^53

   =   0.97999999999999998224...

因此 float 中的 0.98 会稍大,而 double 中的 0.98 会变小.

So the 0.98 will become slightly larger in float and smaller in double.

这篇关于浮点比较中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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