| 1 |
//===----------------------------------------------------------------------===// |
| 2 |
// |
| 3 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
// See https://llvm.org/LICENSE.txt for license information. |
| 5 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 |
// |
| 7 |
//===----------------------------------------------------------------------===// |
| 8 |
|
| 9 |
#ifndef SUPPORT_FP_COMPARE_H |
| 10 |
#define SUPPORT_FP_COMPARE_H |
| 11 |
|
| 12 |
#include <cmath> // for std::abs |
| 13 |
#include <algorithm> // for std::max |
| 14 |
#include <cassert> |
| 15 |
#include <__config> |
| 16 |
|
| 17 |
// See https://www.boost.org/doc/libs/1_70_0/libs/test/doc/html/boost_test/testing_tools/extended_comparison/floating_point/floating_points_comparison_theory.html |
| 18 |
|
| 19 |
template <typename T> |
| 20 |
bool fptest_close(T val, T expected, T eps) { |
| 21 |
_LIBCPP_CONSTEXPR T zero = T(0); |
| 22 |
assert(eps >= zero); |
| 23 |
|
| 24 |
// Handle the zero cases |
| 25 |
if (eps == zero) |
| 26 |
return val == expected; |
| 27 |
if (val == zero) |
| 28 |
return std::abs(expected) <= eps; |
| 29 |
if (expected == zero) |
| 30 |
return std::abs(val) <= eps; |
| 31 |
|
| 32 |
return std::abs(val - expected) < eps && std::abs(val - expected) / std::abs(val) < eps; |
| 33 |
} |
| 34 |
|
| 35 |
template <typename T> |
| 36 |
bool fptest_close_pct(T val, T expected, T percent) { |
| 37 |
assert(percent >= T(0)); |
| 38 |
T eps = (percent / T(100)) * std::max(std::abs(val), std::abs(expected)); |
| 39 |
return fptest_close(val, expected, eps); |
| 40 |
} |
| 41 |
|
| 42 |
#endif // SUPPORT_FP_COMPARE_H |