numerictools.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * NICE-Core - efficient algebra and computer vision methods
  3. * - libfbasics - library of some basic tools
  4. * See file License for license information.
  5. */
  6. #include "core/basics/numerictools.h"
  7. #include <errno.h>
  8. #include <sstream>
  9. #include <clocale>
  10. #include <core/basics/Log.h>
  11. #include <core/basics/Timer.h>
  12. #include <core/basics/Exception.h>
  13. #include <core/basics/Streamable.h>
  14. typedef unsigned int uint;
  15. namespace NICE {
  16. // check if endptr is empty string (except for whitespaces)
  17. static bool isEndPtrOk(char* endptr) {
  18. std::stringstream s(endptr);
  19. // skip whitespaces
  20. ws(s);
  21. return s.eof();
  22. }
  23. // double stringToDouble(const char* s) {
  24. // errno = 0;
  25. // char* endptr;
  26. // const double v = strtod(s, &endptr);
  27. // if (errno != 0 || !isEndPtrOk(endptr)) {
  28. // fthrow(Exception, "Format error in floating point input");
  29. // }
  30. // return v;
  31. // }
  32. double stringToDouble(const char* s) {
  33. char* endptr;
  34. setlocale(LC_NUMERIC, US_ENGLISH_LOCALE);
  35. errno = 0;
  36. const double v = strtod(s, &endptr);
  37. if (errno != 0 || !isEndPtrOk(endptr)) {
  38. std::string st(s);
  39. if (st == "nan") {
  40. return doubleNaN();
  41. } else if (st == "inf") {
  42. return std::numeric_limits<double>::infinity();
  43. } else if (st == "-inf") {
  44. return -std::numeric_limits<double>::infinity();
  45. }
  46. fthrow(Exception, "Format error in floating point input: "
  47. << s << " (" << errno << ")");
  48. }
  49. return v;
  50. }
  51. long stringToInt(const char* s) {
  52. errno = 0;
  53. char* endptr;
  54. const long v = strtol(s, &endptr, 10);
  55. if (errno != 0 || !isEndPtrOk(endptr)) {
  56. fthrow(Exception, "Format error in integer input");
  57. }
  58. return v;
  59. }
  60. void initRand( bool fixedSeed, unsigned int seed ) {
  61. // const double now = Timer::getNow();
  62. // const unsigned int seed = (unsigned int)(now * 1000.0);
  63. // Log::debug() << "now, seed: " << now << ", " << seed << std::endl;
  64. // srand(seed);
  65. if ( fixedSeed )
  66. srand ( (uint)seed );
  67. else
  68. srand((uint)Timer::getMicroseconds());
  69. }
  70. std::string intToString(const int i) {
  71. std::stringstream s;
  72. s << i;
  73. return s.str();
  74. }
  75. std::string doubleToString(const double d, const unsigned int digits,
  76. const bool fixedPoint) {
  77. std::stringstream s;
  78. s.imbue(std::locale(US_ENGLISH_LOCALE));
  79. s.precision(digits);
  80. if (fixedPoint) {
  81. s << std::fixed;
  82. }
  83. s << d;
  84. return s.str();
  85. }
  86. } // namespace