Last active
August 29, 2015 14:19
-
-
Save creative-quant/cbf1a6418c1a28ee0916 to your computer and use it in GitHub Desktop.
Comparing floating point numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* AlmostEqual.h | |
* | |
*/ | |
#ifndef ALMOSTEQUAL_H_ | |
#define ALMOSTEQUAL_H_ | |
// Usable AlmostEqual function - http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm | |
bool AlmostEqual(float A, float B) { | |
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 <= 4) { | |
return true; | |
} | |
return false; | |
} | |
#endif /* ALMOSTEQUAL_H_ */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment