Comparing float and double

☆樱花仙子☆ 提交于 2019-12-17 09:58:16

问题


#include <stdio.h>
int main(void){
    float a = 1.1;
    double b = 1.1;
    if(a == b){
        printf("if block");
    }
    else{
        printf("else block");
    }
    return 0;
}

Prints: else block

#include <stdio.h>
int main(void){
    float a = 1.5;
    double b = 1.5;
    if(a == b){
        printf("if block");
    }
    else{
        printf("else block");
    }
    return 0;
}

Prints: if block

What is the logic behind this?

Compiler used: gcc-4.3.4


回答1:


This is because 1.1 is not exactly representable in binary floating-point. But 1.5 is.

As a result, the float and double representations will hold slightly different values of 1.1.

Here is exactly the difference when written out as binary floating-point:

(float) 1.1 = (0.00011001100110011001101)₂
(double)1.1 = (0.0001100110011001100110011001100110011001100110011010)₂

Thus, when you compare them (and the float version gets promoted), they will not be equal.




回答2:


Must read: What Every Computer Scientist Should Know About Floating-Point Arithmetic




回答3:


The exact value of 1.1 decimal in binary is non-ending fraction 1.00011001100110011001100(1100).... The double constant 1.1 is 53-bit truncation / approximate value of that mantissa. Now this when converted to float, the mantissa will be represented just in 24 bits.

When the float is converted back to double, the mantissa is now back to 53 bits, but all memory of the digits beyond 24 are lost - the value is zero-extended, and now you're comparing (for example, depending on the rounding behaviour)

1.0001100110011001100110011001100110011001100110011001

and

1.0001100110011001100110000000000000000000000000000000

Now, if you used 1.5 instead of 1.1;

1.5 decimal is exactly 1.1 in binary. It can be presented exactly in just 2 bit mantissa, therefore even the 24 bits of float are an exaggeration... what you have is

1.1000000000000000000000000000000000000000000000000000

and

1.10000000000000000000000

The latter, zero extended to a double would be

1.1000000000000000000000000000000000000000000000000000

which clearly is the same number.



来源:https://stackoverflow.com/questions/9014303/comparing-float-and-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!