浮点数字是不相等的,尽管是一样的吗? [英] Float point numbers are not equal, despite being the same?

查看:172
本文介绍了浮点数字是不相等的,尽管是一样的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面输出的节目此编号为不尽相同。它为什么这样做时,这两个数字都是一样的?

 无效的主要(){
    浮动F = 2.7;    如果(F = = 2.7){
        的printf(这是号相同的);
    }其他{
        的printf(这是第一样不);
    }
}


解决方案

编译器转换 2.7 到最近重新presentable 或约2.700000000000000177635683940025046467781067给出的典型 binary64 再<$的presentation C $ C>双击。

当值被分配到浮动,它成为最近的重presentable 浮动或约2.7000000476837158203125。

2.700000000000000177635683940025046467781067不等于2.7000000476837158203125。

如果一个编译器使用浮点/双精度从而重新presents 2.7 究竟 DECIMAL32 / DECIMAL64 ,code将工作作为OP的预期。 使用底层十进制格式是少见的双重新presentation。更为经常的根本双击重新presentation为基地2和这些文物的转换需要编程时要考虑的。

有code被浮动F = 2.5; 浮动值,使用二进制或十进制基础格式,会作出如果(F = = 2.5)真。相同的值高precision 双击重新presentable的究竟的为低precision 浮动

(假设binary32 / binary64浮点)结果
 双击具有重要意义的53位和浮动 24具有关键的是,如果作为一个<$ C $数C>双已其最显著(53-24)位设置为0,当转换为浮动,就会有相同的数值为一个浮动双击。像 1 号, 2.5 2.7000000476837158203125 履行。 (这里忽略的范围内,分普通和NaN问题。)

这是一个原因,确切的浮点比较通常仅在某些情况下完成的。

The program below outputs This No. is not same. Why does it do this when both numbers are the same?

void main() {
    float f = 2.7;

    if(f == 2.7) {
        printf("This No. is same");
    } else {
        printf("This No. is not same");
    }
}

解决方案

The compiler converts 2.7 to the nearest representable double or about 2.700000000000000177635683940025046467781067 given the typical binary64 representation of double.

When the value is assigned to a float, it becomes the nearest representable float or about 2.7000000476837158203125.

2.700000000000000177635683940025046467781067 does not equal 2.7000000476837158203125.

Should a compiler use a float/double which represents 2.7 exactly like with decimal32/decimal64, code would work as OP expected. double representation using an underlying decimal format is rare. Far more often the underlying double representation is base 2 and these conversion artifacts need to be considered when programming.

Had the code been float f = 2.5;, the float and double value, using a binary or decimal underlying format, would have made if (f == 2.5) true. The same value as a high precision double is representable exactly as a low precision float.

(Assuming binary32/binary64 floating point)
double has 53 bits of significance and float has 24. The key is that if the number as a double has its least significant (53-24) bits set to 0, when converted to float, it will have the same numeric value as a float or double. Numbers like 1, 2.5 and 2.7000000476837158203125 fulfill that. (range, sub-normal, and NaN issues ignored here.)

This is a reason why exact floating point comparisons are typically only done in select situations.

这篇关于浮点数字是不相等的,尽管是一样的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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