ALPSCore reference
fp_compare.hpp
Go to the documentation of this file.
1 /*
2  * Copyright (C) 1998-2018 ALPS Collaboration. See COPYRIGHT.TXT
3  * All rights reserved. Use is subject to license terms. See LICENSE.TXT
4  * For use in publications, see ACKNOWLEDGE.TXT
5  */
6 
12 // FIXME! Not tested.
13 
14 #ifndef ALPS_TESTING_FP_COMPARE_HPP_161c4f3bdd53475d8c6ea28232c9653c
15 #define ALPS_TESTING_FP_COMPARE_HPP_161c4f3bdd53475d8c6ea28232c9653c
16 
17 #include <cmath>
18 #include <float.h>
19 
20 namespace alps {
21  namespace testing {
22 
23  namespace detail {
24  // FIXME! There must be somethng usable in Boost
25  template <typename> struct fpconst {};
26 
27  // FIXME! TODO:C++11 use constexpr
28 
29  template <>
30  struct fpconst<double> {
31  static double epsilon() { return DBL_EPSILON; }
32  static double min() {return DBL_MIN; }
33  static double max() {return DBL_MAX; }
34  };
35 
36  template <>
37  struct fpconst<float> {
38  static float epsilon() { return FLT_EPSILON; }
39  static float min() {return FLT_MIN; }
40  static float max() {return FLT_MAX; }
41  };
42  } // ::detail
43 
45  template <typename T>
46  inline bool is_near(const T a, const T b, const T eps)
47  {
48  using std::fabs;
49  if (a==b) return true;
50 
51  static const T FPMIN=detail::fpconst<T>::min();
52  static const T FPMAX=detail::fpconst<T>::max();
53 
54  const double diff=fabs(a-b);
55  if (a==0 || b==0 || diff<FPMIN) return diff < (eps*FPMIN);
56 
57  const double abs_a=fabs(a);
58  const double abs_b=fabs(b);
59  const double sum = (abs_b > FPMAX-abs_a)? FPMAX : (abs_a+abs_b);
60  return diff/sum < eps;
61  }
62 
64  template <typename T>
65  inline bool is_near(const T a, const T b)
66  {
67  static const T EPS=detail::fpconst<T>::epsilon();
68  return is_near(a, b, EPS);
69  }
70 
71  } // ::testing
72 } // ::alps
73 
74 #endif /* ALPS_TESTING_FP_COMPARE_HPP_161c4f3bdd53475d8c6ea28232c9653c */
bool is_near(const T a, const T b, const T eps)
Compares two floating point values, see http://floating-point-gui.de/errors/comparison/.
Definition: fp_compare.hpp:46