retdec
equality.h
Go to the documentation of this file.
1 
7 #ifndef RETDEC_UTILS_EQUALITY_H
8 #define RETDEC_UTILS_EQUALITY_H
9 
10 #include <cmath>
11 
12 namespace retdec {
13 namespace utils {
14 
15 namespace {
16 
27 template<typename T>
28 inline bool areEqualFPWithEpsilon(const T &x, const T &y, const T &epsilon) {
29  // Implementation notes:
30  // - Inspiration was taken from
31  // http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.17. See also
32  // Section 4.2 in [D. Knuth, The Art of Computer Programming, Volume II].
33  // - std::{abs,isnan,isinf}() in cmath are overloaded for floats, doubles, and
34  // long doubles.
35  if (std::isnan(x)) {
36  return std::isnan(y);
37  } else if (std::isnan(y)) {
38  return false;
39  } else if (std::isinf(x)) {
40  return std::isinf(x) == std::isinf(y);
41  } else if (std::isinf(y)) {
42  return false;
43  }
44  return std::abs(x - y) <= epsilon * std::abs(x);
45 }
46 
47 } // anonymous namespace
48 
51 
59 template<typename T>
60 inline bool areEqual(const T &x, const T &y) {
61  return x == y;
62 }
63 
64 // Specialization for floats.
65 template<>
66 inline bool areEqual<float>(const float &x, const float &y) {
67  return areEqualFPWithEpsilon(x, y, 1e-5f);
68 }
69 
70 // Specialization for doubles.
71 template<>
72 inline bool areEqual<double>(const double &x, const double &y) {
73  return areEqualFPWithEpsilon(x, y, 1e-10);
74 }
75 
76 // Specialization for long doubles.
77 template<>
78 inline bool areEqual<long double>(const long double &x, const long double &y) {
79  return areEqualFPWithEpsilon(x, y, 1e-15L);
80 }
81 
83 
84 } // namespace utils
85 } // namespace retdec
86 
87 #endif
bool areEqual< float >(const float &x, const float &y)
Definition: equality.h:66
bool areEqual< double >(const double &x, const double &y)
Definition: equality.h:72
bool areEqual< long double >(const long double &x, const long double &y)
Definition: equality.h:78
bool areEqual(const T &x, const T &y)
Returns true if x is equal to y, false otherwise.
Definition: equality.h:60
Definition: archive_wrapper.h:19