Skip to content

Instantly share code, notes, and snippets.

@creative-quant
Last active August 29, 2015 14:19
Show Gist options
  • Save creative-quant/cbf1a6418c1a28ee0916 to your computer and use it in GitHub Desktop.
Save creative-quant/cbf1a6418c1a28ee0916 to your computer and use it in GitHub Desktop.
Comparing floating point numbers
/*
* 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