Monday, July 9, 2007

How do you compare floating point numbers?

This is Wrong!.


double a, b;

if(a == b)
{
...
}



The above code might not work always. Thats because of the way floating point numbers are stored.

A good way of comparing two floating point numbers is to have a accuracy threshold which is relative to the magnitude of the two floating point numbers being compared.


#include < math.h >
if(fabs(a - b) <= accurary_threshold * fabs(a))


There is a lot of material on the net to know how floating point numbers can be compared. Got for it if you really want to understand.



Another way which might work is something like this. I have not tested it!



int compareFloats(float f1, float f2)
{
char *b1, *b2;
int i;

b1 = (char *)&f1;
b2 = (char *)&f2;

/* Assuming sizeof(float) is 4 bytes) */

for (i = 0; i < 4; i++, b1++, b2++)
{
if (*b1 != *b2)
{
return(NOT_EQUAL); /* You must have defined this before */
}
}

return(EQUAL);
}

7 comments:

  1. I describe a very fast method for comparing floats using a tolerance relative to the magnitude at http://www.randydillon.org/Papers/2007/everfast.htm

    ReplyDelete
  2. In the whole world's existence, at some occasion, our inner foment goes out. It is then bust into zeal at hand an encounter with another magnanimous being. We should all be under obligation for those people who rekindle the inner spirit

    ReplyDelete
  3. //compares if the float f1 is equal with f2 and returns 1 if true and 0 if false
    int compare_float(float f1, float f2)
    {
    float precision = 0.00001;
    if (((f1 - precision) < f2) &&
    ((f1 + precision) > f2))
    {
    return 1;
    }
    else
    {
    return 0;
    }
    }

    You can set the precision of the comparison between the floating point numbers by changing the "precision" variable.

    ReplyDelete
  4. #define EPSILON 0.0001 // Define your own tolerance
    #define FLOAT_EQ(x,v) (((v - EPSILON) < x) && (x <( v + EPSILON)))
    int main()
    {
    float a = 2.501f;
    a *= 1.5134f;
    if (FLOAT_EQ(a, 3.7850)) cout << "Expected value" << endl;
    else cout << "Unexpected value" << endl;
    }

    ReplyDelete
  5. Aewsome. I appreciate the blogger for posting the most excellent thought. thank you for sharing this useful information and i will let know my friends as well.

    ReplyDelete
  6. Hi, i believe that i saw you visited my site so i
    got here to return the choose?.I am trying to find
    issues to improve my website!I suppose its ok to use a few of your concepts!
    !

    My web site: diet plans that work for women

    ReplyDelete
  7. Ilike Hp laserJet Printers.

    Also visit my weblog; xerox phaser 8560mfp

    ReplyDelete