Helpers.hh
00001 #ifndef GAZEBO_MATH_FUNCTIONS_HH 00002 #define GAZEBO_MATH_FUNCTIONS_HH 00003 00004 #include <cmath> 00005 #include <limits> 00006 #include <string> 00007 #include <iostream> 00008 00009 namespace gazebo 00010 { 00011 namespace math 00012 { 00013 static const double NAN_D = std::numeric_limits<double>::quiet_NaN(); 00014 static const double NAN_I = std::numeric_limits<int>::quiet_NaN(); 00015 00016 inline bool equal(const double &_a, const double &_b, 00017 const double &_epsilon) 00018 { 00019 return std::fabs(_a - _b) <= _epsilon; 00020 } 00021 00022 inline bool equal(const float &_a, const float &_b, const float &_epsilon) 00023 { 00024 return std::fabs(_a - _b) <= _epsilon; 00025 } 00026 00027 inline double precision(const double &_a, const unsigned int &_precision) 00028 { 00029 return round(_a * pow(10,_precision)) / pow(10,_precision); 00030 } 00031 00032 inline float precision(const float &_a, const unsigned int &_precision) 00033 { 00034 return roundf(_a * pow(10,_precision)) / pow(10,_precision); 00035 } 00036 00037 inline int parseInt(const std::string& input) 00038 { 00039 const char *p = input.c_str(); 00040 if (!*p || *p == '?') 00041 return NAN_I; 00042 00043 int s = 1; 00044 while (*p == ' ') 00045 p++; 00046 00047 if (*p == '-') 00048 { 00049 s = -1; 00050 p++; 00051 } 00052 00053 double acc = 0; 00054 while (*p >= '0' && *p <= '9') 00055 acc = acc * 10 + *p++ - '0'; 00056 00057 if (*p) 00058 { 00059 std::cerr << "Invalid int numeric format[" << input << "]\n"; 00060 return 0.0; 00061 } 00062 00063 return s * acc; 00064 } 00065 00066 inline double parseFloat(const std::string& input) 00067 { 00068 const char *p = input.c_str(); 00069 if (!*p || *p == '?') 00070 return NAN_D; 00071 int s = 1; 00072 while (*p == ' ') 00073 p++; 00074 00075 if (*p == '-') 00076 { 00077 s = -1; 00078 p++; 00079 } 00080 00081 double acc = 0; 00082 while (*p >= '0' && *p <= '9') 00083 acc = acc * 10 + *p++ - '0'; 00084 00085 if (*p == '.') 00086 { 00087 double k = 0.1; 00088 p++; 00089 while (*p >= '0' && *p <= '9') 00090 { 00091 acc += (*p++ - '0') * k; 00092 k *= 0.1; 00093 } 00094 } 00095 if (*p == 'e') 00096 { 00097 int es = 1; 00098 int f = 0; 00099 p++; 00100 if (*p == '-') 00101 { 00102 es = -1; 00103 p++; 00104 } 00105 else if (*p == '+') 00106 { 00107 es = 1; 00108 p++; 00109 } 00110 while (*p >= '0' && *p <= '9') 00111 f = f * 10 + *p++ - '0'; 00112 00113 acc *= pow(10,f*es); 00114 } 00115 00116 if (*p) 00117 { 00118 std::cerr << "Invalid double numeric format[" << input << "]\n"; 00119 return 0.0; 00120 } 00121 return s * acc; 00122 } 00123 } 00124 } 00125 #endif

1.7.5.1