patterncppMinor
Checking if two floating point numbers are equal
Viewed 0 times
pointarefloatingnumberscheckingequaltwo
Problem
Is this the best way to check if two floating point numbers are equal, or close to being equal?
template
bool IsEqual(T rhs, T lhs)
{
T diff = std::abs(lhs - rhs);
T epsilon = std::numeric_limits::epsilon( ) * std::max(std::abs(rhs), std::abs(lhs));
return diff <= epsilon ;
}Solution
Seems unlikely.
You want to check for something "close to" equal, but you don't say what close to means for you. Assuming it to be a few multiples of epsilon, the following check would seem reasonable:
epsilon from std::numeric_limits is the smallest increment representable by the type (around the value 1).You want to check for something "close to" equal, but you don't say what close to means for you. Assuming it to be a few multiples of epsilon, the following check would seem reasonable:
const int FEW = 10;
T diff = std::abs(lhs - rhs);
T epsilon = std::numeric_limits::epsilon();
return diff < (epsilon * FEW);Code Snippets
const int FEW = 10;
T diff = std::abs(lhs - rhs);
T epsilon = std::numeric_limits<T>::epsilon();
return diff < (epsilon * FEW);Context
StackExchange Code Review Q#17923, answer score: 4
Revisions (0)
No revisions yet.