Compare whether two floating-point numbers are approximately equal à la Knuth up to a given tolerance.
On top of Knuth's tolerance predicate some corner cases are treated and the caller can specify a threshold as last parameter to make the test consider numbers equal if the absolute value of their difference is below of it.
- Parameters
-
[in] | x | First of the two numbers. |
[in] | y | Second of the two numbers. |
[in] | epsilon | The relative tolerance for the test. |
[in] | threshold | Threshold for the number comparison. By default this is zero, implying no threshold is considered. |
- Returns
false
if either x
or y
is not a finite number, provided that the type supports non-numeric representations (i.e. is infinite or NAN);
-
true
if x == y
;
-
true
if x == 0
and if \( |x| \le \varepsilon\);
-
true
if y == 0
and if \( |y| \le \varepsilon\);
-
true
if \( |x - y| \le M_\mathrm{threshold} \);
-
true
if \( |x - y| \le \varepsilon \cdot \max(|x|, |y|) \) (Knuth's tolerance predicate);
-
false
otherwise.
Definition at line 59 of file numerics.h.
62 assert(threshold >= 0);
63 if constexpr (std::numeric_limits<N>::is_iec559) {
64 if (!std::isfinite(x) || !std::isfinite(y)) {
71 return std::abs(y) <= epsilon;
73 return std::abs(x) <= epsilon;
75 return std::abs(x - y) <= threshold ||
76 std::abs(x - y) <= epsilon * std::max(std::abs(x), std::abs(y));