Ask your own question, for FREE!
Computer Science 8 Online
OpenStudy (shiv):

#include int main() { float f1=14.375; float f2=14.385; if(f1==14.375) printf("yes\n"); else {printf("no\n"); if(f2==14.385) printf("yes\n"); else printf("no\n"); return 0; }

OpenStudy (shiv):

help someone the output for this is yes no why??

OpenStudy (anonymous):

If I understand correctly, you're wondering why the ouput is "no" instead of "yes" (what you'd excpect), am I right? The problem has to do with routing. A number like 14.375 might be stored as e.g. 14.375001. And than it obviously is not equal to 14.375 anymore. When comparing floats and doubles, you need to take this rounding into account. DO you have any idea how you can do that?

OpenStudy (shiv):

thanks...but still cant understood perfectly, if we take rounding into account then both the output should come no..????

OpenStudy (rsmith6559):

Floating point is basically a binary scientific notation. It doesn't represent all numbers perfectly. It's usually not a good idea to compare exact floating point values because of this.

OpenStudy (anonymous):

The problem with comparing floating point values is that if there is a very small difference between numbers (like e.g. 0.0000000000000000000001), the number will be different. And rightly so, since your compiler does not know how much precision you want. So you cannot compare floating point numbers directly. Instead, you'll need to compare the difference between the numbers. If e.g. you want a precision of 0.0001, you can check whether or not two numbers are equal (within that precision) by if( fabs( f1 - f2 ) < 0.0001 ) Or in English: if the difference between f1 and f2 is less than 0.0001, then they are considered equal. (N.B. if f2 is larger than f1, the difference will ne negative, and thus smaller than 0.0001. To counter that, I used the fabs to use only the absolute difference).

OpenStudy (shiv):

but why output comes yes on f1=14.375???

OpenStudy (shiv):

how i will come to know when the output will come yes and when no??

OpenStudy (rsmith6559):

Because it's a binary representation, numbers that are related to 2 represent accurately. Numbers that are related to three don't. The first thing that pops out to me is that 14.375 is 14 and 3 / 8. 8 is exactly 2^3.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!