Tuesday, July 14, 2009

C programmers, have you seen this before?

I was comparing two floating point numbers to determine when to exit a loop. One floating point was set to 2 (float1). The other started at 1 (float2) and was incremented by 0.2. The loop was supposed to exit when the second floating point got to 2.2 (as in loop while(float2 %26lt;= float1), but it would always exit at 1.8. The only way I could fix it was to do a (fabs(float1 - float2) %26lt; 0.01), along with an or statement of float1 %26lt; float2.


I watched the numbers in the debugger, and it wasn't as if it said 2.00001 when it incremented to 2. Basically, it looked as if it was saying 2 is not equal to 2. I thought I was going insane!!! How could 2 not be equal to 2??? But I guess with floating points, there some issue with precision?

C programmers, have you seen this before?
Yes. This happens. Its a problem when you're dealing with floating point numbers. Like 1/3, which cannot be represented by a finite set of numbers (3.333....) floating point numbers have some variance.
Reply:Use abs(f1-f2) %26lt; epsilon(very small number) to compare them


No comments:

Post a Comment