user2494601
user2494601

Reputation:

Comparison of one float variable to its contained value

#include<stdio.h>
int main()
{
    float a,b;
    a=4.375;
    b=4.385;

    if(a==4.375)
        printf("YES\n");
    else
        printf("NO\n");

    if(b==4.385)
        printf("YES\n");
    else
        printf("NO\n");

    return 0;
}

Answer of this code :

YES 
NO

I always thought if i compare a float with double value. it will never match to it. unless value is pure integer. but here float "a" has 4.375 is exact in it but "b" doesn't

printf("%0.20f\n",a);
printf("%0.20f\n",b);

This prints :

4.37500000000000000000
4.38500022888183593750



but if i print

printf("%0.20f\n",4.475);

It prints 4.47499990463256835938

How is this rounding effect is showing in some and not in others.

Can anyone explain this. how should "WE" judge when value in float variable will match to that contained in it and when it doesn't ?

Upvotes: 5

Views: 179

Answers (2)

jcoder
jcoder

Reputation: 30035

Floating points aren't magic. They contain an exact value and if you compare it with that they will compare equal. The two problems are 1) Some operations are not always entirely exact due to precision issues. If you add one to a float and then subtract one then adding that one might have causes some loss of precision in the least significant value bits and when you subtract it you don't get back to quite the same value you expect. 2) It is not possible to exactly represent every decimal value in the floating point binary format. For example it is not possible to store the exact value of 0.1 in a floating point binary number in exactly the same way that you can't write the value of 1/3.0 as a decimal value exactly no matter how many digits you use.

But in your case if you store a value and compare it with that same value they SHOULD compare equal as they'll both have the same issues in the same way. Your issue though is that you are not comparing like with like. 4.375 and 4.385 are not floats they are doubles and get converted to be stored so when you compare them later it's possible that the converted value is not quite identical. If you write 4.385f and 4.385f to use float values you should get YES both times.

Upvotes: 1

Deepu
Deepu

Reputation: 7610

The conversion from decimal fraction to a binary fraction is precise only if the decimal fraction can be summed up by binary fractions like 0.5, 0.25, ..., etc.

For example in your case

0.375 = 0.25 + 0.125 = 2-2 + 2-3

So it can be represented exactly by using binary fractions.

Where as the number 0.385 can not be represented by using binary fractions precisely. So numbers like 0.5, 0.25, 0.125, ..., etc. or a combination of these numbers can be represented exactly as floating point numbers. Others like 0.385 will give incorrect results when the comparison or equality operations are performed on them.

Upvotes: 1

Related Questions