Here is how I would test for equality, without a "fudge factor":
if (
// Test 1: Very cheap, but can result in false negatives
a==b ||
// Test 2: More expensive, but comprehensive
std::abs(a-b)<std::abs(std::min(a,b))*std::numeric_limits<double>::epsilon())
std::cout << "The numbers are equal
";
Explanation
The first test is a simple comparison. Of course we all know that comparing double precision values can result in them being deemed unequal, even when they are logically equivalent.
A double precision floating point value can hold the most significant fifteen digits of a number (actually ≈15.955 digits). Therefore, we want to call two values equal if (approximately) their first fifteen digits match. To phrase this another way, we want to call them equal if they are within one scaled epsilon of each other. This is exactly what the second test computes.
You can choose to add more leeway than a single scaled epsilon, due to more significant floating point errors creeping in as a result of iterative computation. To do this, add an error factor to the right hand side of the second test's comparison:
double error_factor=2.0;
if (a==b ||
std::abs(a-b)<std::abs(std::min(a,b))*std::numeric_limits<double>::epsilon()*
error_factor)
std::cout << "The numbers are equal
";
I cannot give you a fixed value for the error_factor
, since it will depend on the amount of error that creeps into your computations. However, with some testing you should be able to find a reasonable value that suits your application. Do keep in mind that adding an (arbitrary) error factor based on speculation alone will put you right back into fudge factor territory.
Summary
You can wrap the following test into a(n inline) function:
inline bool logically_equal(double a, double b, double error_factor=1.0)
{
return a==b ||
std::abs(a-b)<std::abs(std::min(a,b))*std::numeric_limits<double>::epsilon()*
error_factor;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…