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); | |
} |
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
@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
Hi @thm-development,
The
absEpsilon
andrelEpsilon
values depend on the level of precision that you need for your purposes. Ifseem 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.