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 #ifndef SUPPORT_FP_COMPARE_H
9 #define SUPPORT_FP_COMPARE_H
10
11 #include <cmath> // for std::abs
12 #include <algorithm> // for std::max
13 #include <cassert>
14
15 // 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
16
17 template<typename T>
fptest_close(T val,T expected,T eps)18 bool fptest_close(T val, T expected, T eps)
19 {
20 constexpr T zero = T(0);
21 assert(eps >= zero);
22
23 // Handle the zero cases
24 if (eps == zero) return val == expected;
25 if (val == zero) return std::abs(expected) <= eps;
26 if (expected == zero) return std::abs(val) <= eps;
27
28 return std::abs(val - expected) < eps
29 && std::abs(val - expected)/std::abs(val) < eps;
30 }
31
32 template<typename T>
fptest_close_pct(T val,T expected,T percent)33 bool fptest_close_pct(T val, T expected, T percent)
34 {
35 constexpr T zero = T(0);
36 assert(percent >= zero);
37
38 // Handle the zero cases
39 if (percent == zero) return val == expected;
40 T eps = (percent / T(100)) * std::max(std::abs(val), std::abs(expected));
41
42 return fptest_close(val, expected, eps);
43 }
44
45
46 #endif // SUPPORT_FP_COMPARE_H
47