vrecko
virtual reality framework
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
RealCmp.h
Go to the documentation of this file.
1 #ifndef REAL_CMP_H
2 #define REAL_CMP_H
3 
4 #include <sstream>
5 #include <string>
6 #include <iomanip>
7 
8 /*adtmag.com*/
9 template <class T>
10 class RealCmp
11 {
12  enum FloatCmp {
13  FC_LT,
14  FC_GT,
15  FC_EQ
16  };
17 
18 public:
19  static FloatCmp comparator(T a, T b) {
20  std::string s, n;
21  int exp1, exp2;
22 
23  s = toString(a);
24  n = s.substr(s.rfind("e")+1);
25  exp1 = atof(n.c_str());
26 
27  s = toString(b);
28  n = s.substr(s.rfind("e")+1);
29  exp2 = atof(n.c_str());
30 
31  FloatCmp result;
32  if ((exp1 + 6) < exp2){
33  result = FC_LT;
34  }
35  else if (exp1 > (exp2 + 6)) {
36  result = FC_GT;
37  }
38  else if ((abs(a-b) / (b==0.0 ? 1.0 : abs(b))) < 0.00001/*std::numeric_limits<float>::epsilon()*/) {
39  result = FC_EQ;
40  }
41  else if (a < b) {
42  result = FC_LT;
43  }
44  else if (a > b) {
45  result = FC_GT;
46  }
47 
48  return result;
49  }
50 
51  static inline bool compareLT(T a, T b) { return (comparator(a, b) == FC_LT); }
52 
53  static inline bool compareGT(T a, T b) { return (comparator(a, b) == FC_GT); }
54 
55  static inline bool compareEQ(T a, T b) { return (comparator(a, b) == FC_EQ); }
56 
57  static inline bool compareLTEQ(T a, T b) { return ((comparator(a, b) == FC_LT) || (comparator(a, b) == FC_EQ)); }
58 
59  static inline bool compareGTEQ(T a, T b) { return ((comparator(a, b) == FC_GT) || (comparator(a, b) == FC_EQ)); }
60 
61 private:
62  static std::string toString(T number) {
63  std::stringstream sstr;
64  sstr << std::scientific << number;
65  return sstr.str();
66  }
67 
68 };
69 
70 #endif
71