浮VS双对比 [英] float vs double comparison

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

问题描述

int main(void)
{
    float me = 1.1;       
    double you = 1.1;   

    if ( me == you ) {
        printf("I love U");
    } else {
        printf("I hate U");
    }
}

这将打印我恨U。为什么呢?

This prints "I hate U". Why?

推荐答案

花车使用二进制小数。如果转换 1.1 浮动,这将导致一个二进制重新presentation。
权利如果二进制点半的数字的权重,各比特尽可能为小数,它除以十。左双点位(以十倍的十进制)。

Floats use binary fraction. If you convert 1.1 to float, this will result in a binary representation. Each bit right if the binary point halves the weight of the digit, as much as for decimal, it divides by ten. Bits left of the point double (times ten for decimal).

in decimal: ... 0*2 + 1*1 + 0*0.5 + 0*0.25 + 0*0.125 + 1*0.0625 + ...
binary:          0    1  .  0       0        0         1          ...
2's exp:         1    0    -1      -2       -3        -4
(exponent to the power of 2)

问题是, 1.1 不能准确地转换成二进制再presentation。对于双,有,但是,更显著数字比浮动。

Problem is that 1.1 cannot be converted exactly to binary representation. For double, there are, however, more significant digits than for float.

如果你比较的值,首先,浮子被转换为加倍。但是,随着电脑不知道原来的十进制值,它只是填充新的双的尾部位数与所有 0 ,而双值更precise 。因此,无论就比较不相等。

If you compare the values, first, the float is converted to double. But as the computer does not know about the original decimal value, it simply fills the trailing digits of the new double with all 0, while the double value is more precise. So both do compare not equal.

本使用浮点数时是一个常见的​​问题。对于这个问题和其他原因(例如舍入误差),你不应该使用精确比较相等/不等),但使用范围从0不同最小的值进行比较:

This is a common pitfall when using floats. For this and other reasons (e.g. rounding errors), you should not use exact comparison for equal/unequal), but a ranged compare using the smallest value different from 0:

#include "float.h"

...
// check for "almost equal"
if ( fabs(fval - dval) <= FLT_EPSILON )
    ...

请注意FLT_EPSILON的使用,这是一个precision 浮动值上述数值。还要注意&LT; = ,而不是&LT; ,因为后者实际上将需要精确匹配)

Note the usage of FLT_EPSILON, which is the aforementioned value for single precision float values. Also note the <=, not <, as the latter will actually require exact match).

如果你比较两个双打,你可以使用DBL_EPSILON,但要小心这一点。

If you compare two doubles, you might use DBL_EPSILON, but be careful with that.

根据中间计算,公差必须增加(不能进一步降低比小量),如舍入误差等,将总结。一般的花车不与约precision,转换和舍入错误的假设原谅。

Depending on intermediate calculations, the tolerance has to be increased (you cannot reduce it further than epsilon), as rounding errors, etc. will sum up. Floats in general are not forgiving with wrong assumptions about precision, conversion and rounding.

编辑:

正如@chux建议,这可能工作不按预期较大的值,你必须按指数比例EPSILON。这符合我说:浮动比较是不是整数比较简单。比较之前想想。

As suggested by @chux, this might not work as expected for larger values, as you have to scale EPSILON according to the exponents. This conforms to what I stated: float comparision is not that simple as integer comparison. Think about before comparing.

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

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