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

Hi @thm-development,

The absEpsilon and relEpsilon values depend on the level of precision that you need for your purposes. If

absEpsilon is 1e-3 relEpsilon is 1e-6

seem to work for your use case, I would go with them.

I want to mention that this code snippet is an excerpt from a website that I consider one of the best resources in C++ on the web. The algorithm and logic behind it is explained there.

Hope this helps. If you have any other questions, please do.

@thm-development
Copy link

Hello,
thank you very much for your answer.
I have read the post on LearnCpp site and the author uses 1e-12 for the absEpsilon and 1e-8 for the relEpsilon !
I'll try this and analyse the results. Maybe it's a good idea to use an absEpsilon smaller than the relEpsilon.
Thanks again for your answer.
Best reagrds

@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