Search code examples
cfloating-pointfloating-point-conversion

Comparing float and double


#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


Solution

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