numerictools.h 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. #ifndef _NUMERICTOOLS_FBASICS_H
  2. #define _NUMERICTOOLS_FBASICS_H
  3. /*
  4. * NICE-Core - efficient algebra and computer vision methods
  5. * - libfbasics - library of some basic tools
  6. * See file License for license information.
  7. */
  8. // STL includes
  9. #include <cmath>
  10. #include <math.h>
  11. #include <stdlib.h>
  12. #include <limits>
  13. #include <string>
  14. #ifdef LIMUN_AIBO_MODE
  15. // some functions missing in math.h (NOT in linum namespace!!)
  16. inline float roundf(float x) {
  17. return floor(x + 0.5);
  18. }
  19. inline double round(double x) {
  20. return floor(x + 0.5);
  21. }
  22. inline long double roundl(long double x) {
  23. return floor(x + 0.5);
  24. }
  25. inline long lroundf(float x) {
  26. return (long) floor(x + 0.5);
  27. }
  28. inline long lround(double x) {
  29. return (long) floor(x + 0.5);
  30. }
  31. inline long lroundl(long double x) {
  32. return (long) floor(x + 0.5);
  33. }
  34. #endif // LIMUN_AIBO_MODE
  35. namespace NICE {
  36. /**
  37. * Is a numerical value zero?
  38. */
  39. template<class T>
  40. inline bool isZero(const T& x) {
  41. return x == (T)0;
  42. }
  43. /**
  44. * Is a numerical value zero up to a tolerance?
  45. */
  46. inline bool isZero(float x, float tolerance) {
  47. return fabs(x) < tolerance;
  48. }
  49. /**
  50. * Is a numerical value zero up to a tolerance?
  51. */
  52. inline bool isZero(double x, double tolerance) {
  53. return fabs(x) < tolerance;
  54. }
  55. /**
  56. * Is a numerical value zero?
  57. * Specialization for floating point: Zero up to machine precision?
  58. */
  59. template<>
  60. inline bool isZero(const float& x) {
  61. return isZero(x, std::numeric_limits<float>::epsilon());
  62. }
  63. /**
  64. * Is a numerical value zero?
  65. * Specialization for floating point: Zero up to machine precision?
  66. */
  67. template<>
  68. inline bool isZero(const double& x) {
  69. return isZero(x, std::numeric_limits<double>::epsilon());
  70. }
  71. /**
  72. * Is a numerical value almost zero ? :) up to 1e-15
  73. */
  74. inline bool almostZero(const double a) {
  75. return (fabs(a)<1e-15);
  76. }
  77. /**
  78. * Is \c x = \c y up to a tolerance?
  79. */
  80. inline bool isEqual(float x, float y, float tolerance) {
  81. return fabs(x - y) < tolerance;
  82. }
  83. /**
  84. * Is \c x = \c y up to a tolerance?
  85. */
  86. inline bool isEqual(double x, double y, double tolerance) {
  87. return fabs(x - y) < tolerance;
  88. }
  89. /**
  90. * Is \c x = \c y up to machine precision?
  91. */
  92. inline bool isEqual(float x, float y) {
  93. return isEqual(x, y, std::numeric_limits<float>::epsilon());
  94. }
  95. /**
  96. * Is \c x = \c y up to machine precision?
  97. */
  98. inline bool isEqual(double x, double y) {
  99. return isEqual(x, y, std::numeric_limits<double>::epsilon());
  100. }
  101. /**
  102. * Sign of a numerical value?
  103. * (For floating point values, zero is checked up to machine precision,
  104. * see isZero()).
  105. */
  106. template<class T>
  107. inline T sign(const T& x) {
  108. if (isZero(x)) {
  109. return (T)0;
  110. } else if (x > (T)0) {
  111. return (T)1;
  112. } else {
  113. return (T)(-1);
  114. }
  115. }
  116. /**
  117. * Absolute value (as std::abs() or fabs() for floating point values).
  118. */
  119. template<class T>
  120. inline T absolute(const T& x) {
  121. //return std::abs(x);
  122. if (x >= T(0)) {
  123. return x;
  124. } else {
  125. return -x;
  126. }
  127. }
  128. /**
  129. * Absolute value (as fabs()).
  130. */
  131. template<>
  132. inline float absolute(const float& x) {
  133. return (float) fabs(x);
  134. }
  135. /**
  136. * Absolute value (as fabs()).
  137. */
  138. template<>
  139. inline double absolute(const double& x) {
  140. return (double) fabs(x);
  141. }
  142. /**
  143. * Impose the sign of a numerical value to the sign of another value.
  144. * (For floating point values, zero is checked/handled up to machine precision,
  145. * see isZero()).
  146. * @param x The input value
  147. * @param s The value supplying the sign (its absolute value may be arbitrary)
  148. * @return \c x with the same sign as \c s
  149. */
  150. template<class T>
  151. inline T imposeSign(const T& x, const T& s) {
  152. return absolute(x) * sign(s);
  153. }
  154. /**
  155. * Square.
  156. */
  157. template<class T>
  158. inline T square(const T& t) {
  159. return t * t;
  160. }
  161. /**
  162. * Cube.
  163. */
  164. template<class T>
  165. inline T cube(const T& t) {
  166. return t * t * t;
  167. }
  168. /**
  169. * Cube root: t^(1/3)
  170. */
  171. inline double cubeRoot(const double& t) {
  172. return sign(t) * pow(fabs(t), 1.0 / 3.0);
  173. }
  174. /**
  175. * Check if a floating point value is NaN
  176. */
  177. inline bool isNaN(double x) {
  178. #if (__GNUC__ > 3)
  179. return std::isnan(x);
  180. #else
  181. return x != x;
  182. #endif
  183. }
  184. /**
  185. * Check if a floating point value is NaN
  186. */
  187. inline bool isNaN(float x) {
  188. #if (__GNUC__ > 3)
  189. return std::isnan(x);
  190. #else
  191. return x != x;
  192. #endif
  193. }
  194. /**
  195. * Create NaN
  196. */
  197. inline double doubleNaN() {
  198. double zero = 1.0;
  199. zero -= zero;
  200. return 0.0 / zero;
  201. }
  202. /**
  203. * Create NaN
  204. */
  205. inline float floatNaN() {
  206. float zero = 1.0f;
  207. zero -= zero;
  208. return 0.0f / zero;
  209. }
  210. /**
  211. * Restrict \c value to be within [\c min, \c max].
  212. */
  213. template<class T>
  214. inline const T& limitValue(const T& value, const T& min, const T& max) {
  215. if (value < min) {
  216. return min;
  217. } else if (value > max) {
  218. return max;
  219. } else {
  220. return value;
  221. }
  222. }
  223. /**
  224. * Degree to radian.
  225. */
  226. inline double degreeToRadian(double a) {
  227. return a * M_PI / 180.0;
  228. }
  229. /**
  230. * Radian to degree.
  231. */
  232. inline double radianToDegree(double a) {
  233. return a / M_PI * 180.0;
  234. }
  235. /**
  236. * Normalize an angle to be between 0 and 2 Pi.
  237. */
  238. inline double normalizeAngle(double a) {
  239. const double TWO_PI = 2.0 * M_PI;
  240. return a - floor(a / TWO_PI) * TWO_PI;
  241. }
  242. /**
  243. * Initialize random number generator.
  244. */
  245. void initRand( bool fixedSeed = false, unsigned int seed = 0 );
  246. /**
  247. * A pseudo random number in the range [0,limit), based on \c rand().
  248. * (Initialize generator with \c initRand()).
  249. */
  250. inline int randInt(const int limit) {
  251. if (limit == 0) {
  252. return 0;
  253. } else {
  254. return rand() % limit;
  255. }
  256. }
  257. /**
  258. * A pseudo random number in the range [0,1), based on \c rand().
  259. * (Initialize generator with \c initRand()).
  260. */
  261. inline double randDouble() {
  262. return ((double)rand() / ((double)(RAND_MAX)+1.0));
  263. }
  264. /**
  265. * A pseudo random number in the range [0,limit), based on \c rand().
  266. * (Initialize generator with \c initRand()).
  267. */
  268. inline double randDouble(const double limit) {
  269. return ((double)rand() / ((double)(RAND_MAX)+1.0)) * limit;
  270. }
  271. /**
  272. * A pseudo random number in the range [0,1), based on \c rand().
  273. * (Initialize generator with \c initRand()).
  274. */
  275. inline float randFloat() {
  276. return ((float)rand() / ((float)(RAND_MAX)+1.0f));
  277. }
  278. /**
  279. * A pseudo random number in the range [0,limit), based on \c rand().
  280. * (Initialize generator with \c initRand()).
  281. */
  282. inline float randFloat(const float limit) {
  283. return ((float)rand() / ((float)(RAND_MAX)+1.0f)) * limit;
  284. }
  285. /**
  286. * A pseudo random number generated using a normal distribution
  287. * with an arbitrary standard deviation \c s and zero mean.
  288. */
  289. inline double randGaussDouble ( const double stddev ) {
  290. // adapted from k_reconstruction (Olaf Kähler)
  291. double r1, r2, d;
  292. do {
  293. r1 = 2.0 * randDouble() - 1.0;
  294. r2 = 2.0 * randDouble() - 1.0;
  295. d = r1*r1 + r2*r2;
  296. } while ((d >= 1.0)||(isZero(d)));
  297. d = sqrt((-2.0 * log(d))/d);
  298. double y1 = r1*d;
  299. // y2 = r2*d; this is another random variable
  300. return y1*stddev;
  301. }
  302. /**
  303. * If \c x is NaN, return infinity, x otherwise.
  304. */
  305. inline double nanToInf(double x) {
  306. if (isNaN(x)) {
  307. return std::numeric_limits<double>::infinity();
  308. } else {
  309. return x;
  310. }
  311. }
  312. /**
  313. * Convert string to double, including inf and nan.
  314. * @param s Input string
  315. * @return the double represented by s
  316. * @throw Exception if format not ok
  317. */
  318. double stringToDouble(const char* s);
  319. inline double stringToDouble(std::string s) {
  320. return stringToDouble(s.c_str());
  321. }
  322. /**
  323. * Read double from istream, including inf and nan.
  324. *
  325. * Example1: double x; cin >> x;
  326. *
  327. * Example2: double y; readDouble(y);
  328. *
  329. * If a correct double can be read from the stream,
  330. * both examples do the same. In case of inf and nan,
  331. * only the second version reads correctly.
  332. * Also: errors are signaled differently.
  333. *
  334. * @param s Input string
  335. * @return the double represented by s
  336. * @throw Exception if format not ok
  337. */
  338. inline double readDouble(std::istream& str) {
  339. std::string s;
  340. str >> s;
  341. return stringToDouble(s);
  342. }
  343. /**
  344. * Convert string to int.
  345. * @param s Input string
  346. * @return the int represented by s
  347. * @throw Exception if format not ok
  348. */
  349. long stringToInt(const char* s);
  350. inline long stringToInt(std::string s) {
  351. return stringToInt(s.c_str());
  352. }
  353. /**
  354. * @brief Convert an integer into a string
  355. */
  356. std::string intToString(const int i);
  357. /**
  358. * @brief Convert an integer into a string of fixed length, add leading zeros if needed.
  359. * @author Alxander Freytag
  360. * @date 13-01-2014 (dd-mm-yyyy)
  361. *
  362. * @param i - number to convert
  363. * @param length - resulting length of string including leading zeros
  364. * @return string
  365. */
  366. std::string intToString(const int i, const uint & length);
  367. /**
  368. * Convert a double into a string.
  369. */
  370. std::string doubleToString(const double d, const unsigned int digits = 6,
  371. const bool fixedPoint = false);
  372. /**
  373. * Round a floating point value and convert to int.
  374. */
  375. inline int roundInt(double d) {
  376. return int(round(d));
  377. }
  378. /**
  379. * Round a floating point value and convert to int.
  380. */
  381. inline int roundInt(float d) {
  382. return int(roundf(d));
  383. }
  384. /**
  385. * @brief Compute number of digits (including sign) of a given number w.r.t. a specified base (ONLY USEFUL FOR INT-LIKE VARIABLES)
  386. * @author Alexander Freytag
  387. * @date 13-01-2014 (dd-mm-yyyy)
  388. *
  389. * @param number
  390. * @param base ( default is 10).
  391. * @return int
  392. **/
  393. template <class T>
  394. int getNumDigits(T number, T base = 10 )
  395. {
  396. int digits ( 0 );
  397. // note: only possible, because we call it using call-by-value!
  398. while ( number )
  399. {
  400. number /= base;
  401. digits++;
  402. }
  403. return digits;
  404. }
  405. } // namespace
  406. #endif // _NUMERICTOOLS_FBASICS_H