0.4) printf("It is greater"); if(f==0.4) printf("It is equal");" /> 0.4) printf("It is greater"); if(f==0.4) printf("It is equal");" /> 0.4) printf("It is greater"); if(f==0.4) printf("It is equal");"/>

Floating point comparision

83 Views Asked by At
#include <stdio.h>
int main()
{
    float f; 
    f = 0.4;
    if(f<0.4)
       printf("It is less");
    if(f>0.4)
       printf("It is greater");
    if(f==0.4)
       printf("It is equal");
}

I am not able to get why the output is showing "It is greater".

I get that 0.4 converted to binary representation is 0x3ECCCCCD, which is 4.000000059604644775390625E-1. The doubt is if f stores this rounded value, why 0.4 in the comparison is exact. If both f and 0.4 gets rounded, the output should have been "It is equal".

I tried with f = 0.5, it is showing "It is equal".

While f=0.9, it is showing "It is less".

Please take note that there is no arithmetic at all.

1

There are 1 best solutions below

2
Deduplicator On

While f is a float, all your literals are double.

If you ask nicely, the compiler will even warn you about the assignment:

warning: conversion from 'double' to 'float' changes value from '4.0000000000000002e-1' to '4.00000006e-1f' [-Wfloat-conversion]

Unfortunately, it cannot warn about the comparison, because simply widening the smaller type is nearly always what you want, and was thus codified.

Anyway, floating-point math is dangerous and surprising for the uninitiated:
Is floating point math broken?