This is also known as "fuzzy comparison", allowing the two values to differ a little bit (tolerance, also known as "epsilon"). Typically, such an epsilon value is around 1E-6
to 1E-10
, but you find applications in which smaller or greater values are better suitable: in your example the epsilon shouldn't be less than 1E-2 = 0.01
.
Once you found an epsilon value which suits your needs, you could write the following set of comparison functions like the following (written in the common subset of C and C++; they should work for almost every object-oriented / procedural language with minor changes):
const double fuzzyEpsilon = 1E-6; // just an example!
bool fuzzyEqual(double a, double b) {
return (abs(a - b) <= fuzzyEpsilon);
}
bool fuzzyUnqual(double a, double b) {
return (abs(a - b) > fuzzyEpsilon);
}
int fuzzyCompare(double a, double b) {
return ((a - b) > fuzzyEpsilon) - ((b - a) > fuzzyEpsilon);
}
The third function returns a code of -1
, 0
, 1
if a < b
, a == b
, a > b
respectively with fuzzy comparison (analogous to strcmp
). The implementation assumes that the programming language implicitly converts boolean values to 0
(false) and 1
(true). If not, use the following:
int fuzzyCompare(double a, double b) {
return (a - b) > fuzzyEpsilon ? 1 :
((b - a) > fuzzyEpsilon ? -1 : 0);
}