Error while comparing Float variable
Dear friends,
Please take a look at the following code. Its storing .7 to b and comparing b with .7 . But getting just the opposite of expected result!!
Please explain!
(Three is expected o/p but we get two when run)
Code:
#include<stdio.h>
int main(int argc,char **argv)
{
float a=0.5,b=0.7;
if(b<0.7)
{
if(a<0.5)
{
printf("\nONe");
}
else
{
printf("\nTwo");
}
}
else
{
printf("\nThree");
}
return 0;
}
Re: Error while comparing Float variable
This is probably due to floating point inaccuracy, so you might check if (b < 0.7 + epsilon) instead, where epsilon is some small value.
By the way, please post your properly indented code in [code][/code] bbcode tags.
Re: Error while comparing Float variable
Quote:
Originally Posted by
laserlight
This is probably due to floating point inaccuracy, so you might check if (b < 0.7 + epsilon) instead, where epsilon is some small value.
By the way, please post your properly indented code in [code][/code] bbcode tags.
Sorry about not useing <code> tags.
One hint : If we use .7f in all places, this works fine! Anyone explain?
Re: Error while comparing Float variable
Quote:
Originally Posted by cijothomas
If we use .7f in all places, this works fine! Anyone explain?
As far as I can tell, 0.7 cannot be precisely represented in binary, so floating point inaccuracy would still apply. My guess is that once you correctly switch to using float literals, the inaccuracy is the same in both cases, so your answer is consistent. Nonetheless, using an epsilon would still be good idea, methinks.
Re: Error while comparing Float variable
laserlight explain it...
Quote:
so you might check if (b < 0.7 + epsilon) instead
using f you set the value 0.7 as float, in the same range of b
Re: Error while comparing Float variable
Re: Error while comparing Float variable
Thanks for replying :)
Now i understand the things better :)