Wednesday, April 29, 2009

"Unit in the last place" floating point test

For about the third time, I have needed to look up how to code the Unit in the last place floating point test so I'm going to post this link so I can find it.

And to protect from that going dead the final code:

// Usable AlmostEqual function
bool AlmostEqual2sComplement(float A, float B, int maxUlps)
// Make sure maxUlps is non-negative and small enough that the
// default NAN won't compare as equal to anything.
assert(maxUlps > 0 && maxUlps < 4 * 1024 * 1024);
int aInt = *(int*)&A;
// Make aInt lexicographically ordered as a twos-complement int
if (aInt < 0)
aInt = 0x80000000 - aInt;
// Make bInt lexicographically ordered as a twos-complement int
int bInt = *(int*)&B;
if (bInt < 0)
bInt = 0x80000000 - bInt;
int intDiff = abs(aInt - bInt);
if (intDiff <= maxUlps)
return true;
return false;

No comments:

Post a Comment