maths: avoid division by zero in relatively_equal

This commit is contained in:
Danny Robson 2018-03-27 16:14:41 +11:00
parent 8777d32b94
commit 046e6182e7

View File

@ -81,9 +81,14 @@ namespace util {
///////////////////////////////////////////////////////////////////////////
// Comparisons
inline bool
relatively_equal (float a, float b, float percentage)
relatively_equal (float truth, float test, float percentage)
{
return std::abs (1 - b / a ) < percentage;
// we want to do 1 - b / a, but a might be zero. if we have FE_INVALID
// enabled then we'll pretty quickly throw an exception.
//
// instead we use |a - b | / (1 + |truth|). note that it's not as
// accurate when the test values aren't close to 1.
return std::abs (truth - test) / (1 + std::abs (truth)) < percentage;
}
//-------------------------------------------------------------------------