fp_compare.h 1.4 KB

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