Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing float and double in C

I wrote the following code to compare between a float variable and a double variable in C.

int main()
{
    float f = 1.1;
    double d = 1.1;

    if(f==d)
        printf("EQUAL");

    if(f < d)
        printf("LESS");

    if(f > d)
        printf("GREATER");

    return 0;
}

I am using an online C compiler here to compile my code.

I know that EQUAL will never be printed for recurring decimals. However what I expect should be printed is LESS since double should have a higher precision and therefore should be closer to the actual value of 1.1 than float is. As far as I know, in C when you compare float and double, the mantissa of the float is zero-extended to double, and that zero-extended value should always be smaller.

Instead in all situations GREATER is being printed. Am I missing something here?

like image 996
Rijul Ganguly Avatar asked Dec 08 '22 11:12

Rijul Ganguly


1 Answers

The exact value of the closest float to 1.1 is 1.10000002384185791015625. The binary equivalent is 1.00011001100110011001101

The exact value of the closest double to 1.1 is 1.100000000000000088817841970012523233890533447265625. The binary equivalent is 1.0001100110011001100110011001100110011001100110011010.

Lining up the two binary numbers next to each other:

1.00011001100110011001101
1.0001100110011001100110011001100110011001100110011010

The first few truncated bits for rounding to float are 11001100, which is greater than half, so the conversion to float rounded up, making its least significant bits 11001101. That rounding resulted in the most significant difference being a 1 in the float in a bit position that is 0 in the double. The float is greater than the double, regardless of values of bits of lower significance being zero in the float extended to double, but non-zero in the double.

like image 50
Patricia Shanahan Avatar answered Dec 29 '22 11:12

Patricia Shanahan