|
-
November 30th, 2008, 09:47 AM
#1
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;
}
Last edited by cijothomas; November 30th, 2008 at 10:05 AM.
Reason: to <code>
-
November 30th, 2008, 09:54 AM
#2
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.
-
November 30th, 2008, 10:03 AM
#3
Re: Error while comparing Float variable
 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?
-
November 30th, 2008, 10:16 AM
#4
Re: Error while comparing Float variable
 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.
-
November 30th, 2008, 10:21 AM
#5
Re: Error while comparing Float variable
laserlight explain it...
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
-
November 30th, 2008, 11:00 AM
#6
Re: Error while comparing Float variable
-
November 30th, 2008, 11:37 AM
#7
Re: Error while comparing Float variable
Thanks for replying
Now i understand the things better
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|