numerictools.h 10.0 KB

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