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