-
-
Save aronskaya/a92e17a1a1bdff8401c806ce77610ef2 to your computer and use it in GitHub Desktop.
#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); | |
} |
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.
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!
Hello,
I'm working on a software and I need to check if 2 double values are equal with a given precision (number of significant digits in the decimal part). Your function seems to be what I need but I've a question : what kind of value may I use for relEpsilon ?
I tried with a relEpsilon smaller than absEpsilon :
for example if absEpsilon is 1e-3 relEpsilon is 1e-6 and it seems to give good results.
Thanks for your answer.
Regards