Last active
April 4, 2021 08:36
-
-
Save aronskaya/a92e17a1a1bdff8401c806ce77610ef2 to your computer and use it in GitHub Desktop.
[Comparing floats Knuth]
This file contains 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
#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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@tdm-development, you are very welcome! Good luck!