Skip to content

Instantly share code, notes, and snippets.

@aronskaya
Last active April 4, 2021 08:36
Show Gist options
  • Save aronskaya/a92e17a1a1bdff8401c806ce77610ef2 to your computer and use it in GitHub Desktop.
Save aronskaya/a92e17a1a1bdff8401c806ce77610ef2 to your computer and use it in GitHub Desktop.
[Comparing floats Knuth]
#include <cmath>
// return true if the difference between a and b is less than absEpsilon (a very small number, e.g. 1e-12), or within relEpsilon percent of the larger of a and b
bool approximatelyEqualAbsRel(double a, double b, double absEpsilon, double relEpsilon)
{
// Check if the numbers are really close -- needed when comparing numbers near zero.
double diff = fabs(a - b);
if (diff <= absEpsilon)
return true;
// Otherwise fall back to Knuth's algorithm
return diff <= ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * relEpsilon);
}
@aronskaya
Copy link
Author

@tdm-development, you are very welcome! Good luck!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment