numerictools.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. namespace NICE {
  15. // check if endptr is empty string (except for whitespaces)
  16. static bool isEndPtrOk(char* endptr) {
  17. std::stringstream s(endptr);
  18. // skip whitespaces
  19. ws(s);
  20. return s.eof();
  21. }
  22. // double stringToDouble(const char* s) {
  23. // errno = 0;
  24. // char* endptr;
  25. // const double v = strtod(s, &endptr);
  26. // if (errno != 0 || !isEndPtrOk(endptr)) {
  27. // fthrow(Exception, "Format error in floating point input");
  28. // }
  29. // return v;
  30. // }
  31. double stringToDouble(const char* s) {
  32. char* endptr;
  33. setlocale(LC_NUMERIC, US_ENGLISH_LOCALE);
  34. errno = 0;
  35. const double v = strtod(s, &endptr);
  36. if (errno != 0 || !isEndPtrOk(endptr)) {
  37. std::string st(s);
  38. if (st == "nan") {
  39. return doubleNaN();
  40. } else if (st == "inf") {
  41. return std::numeric_limits<double>::infinity();
  42. } else if (st == "-inf") {
  43. return -std::numeric_limits<double>::infinity();
  44. }
  45. fthrow(Exception, "Format error in floating point input: "
  46. << s << " (" << errno << ")");
  47. }
  48. return v;
  49. }
  50. long stringToInt(const char* s) {
  51. errno = 0;
  52. char* endptr;
  53. const long v = strtol(s, &endptr, 10);
  54. if (errno != 0 || !isEndPtrOk(endptr)) {
  55. fthrow(Exception, "Format error in integer input");
  56. }
  57. return v;
  58. }
  59. void initRand( bool fixedSeed, unsigned int seed ) {
  60. // const double now = Timer::getNow();
  61. // const unsigned int seed = (unsigned int)(now * 1000.0);
  62. // Log::debug() << "now, seed: " << now << ", " << seed << std::endl;
  63. // srand(seed);
  64. if ( fixedSeed )
  65. srand ( (uint)seed );
  66. else
  67. srand((uint)Timer::getMicroseconds());
  68. }
  69. std::string intToString(const int i) {
  70. std::stringstream s;
  71. s << i;
  72. return s.str();
  73. }
  74. std::string doubleToString(const double d, const unsigned int digits,
  75. const bool fixedPoint) {
  76. std::stringstream s;
  77. s.imbue(std::locale(US_ENGLISH_LOCALE));
  78. s.precision(digits);
  79. if (fixedPoint) {
  80. s << std::fixed;
  81. }
  82. s << d;
  83. return s.str();
  84. }
  85. } // namespace