I defined a comparison function for doubles that uses an epsilon, as suggested in: What is the most effective way for float and double comparison?. Two doubles differ if their absolute difference is less than epsilon.
If I have doubles d1 and d2, with d2 = d1+epsilon, d1 should not be equal to d2 since they differ by epsilon. Right?
It works with some values, but not all the time. It might be related to the architecture or to the compiler? What should I do to improve my comparison function?
#include <iomanip> // For std::setprecision
#include <iostream>
#include "math.h" // For fabs
const double epsilon = 0.001;
bool equal(const double &d1, const double &d2)
{
return fabs(d1-d2) < epsilon;
}
int main()
{
double d1 = 3.5;
double d2 = d1+epsilon;
// d2 = d1 + epsilon should not be equal to d1.
std::cout << std::setprecision(16) << "d1 = " << d1 << " d2 = " << d2 << std::endl;
bool eq = equal(d1,d2);
if (eq)
{
std::cout << "They should not be equal, but they are!" << std::endl;
}
else
{
std::cout << "They are not equal. OK!" << std::endl;
}
}
Output on my machine:
d1 = 3.5 d2 = 3.501
They should not be equal, but they are!