Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of numeric_limits<double>::digits10

Tags:

c++

stl

What is the precise meaning of numeric_limits::digits10? Some other related questions in stackoverflow made me think it is the maximum precision of a double, but

  • The following prototype starts working (sucess is true) when precision is greater that 17 ( == 2+numeric_limits::digits10)
  • With STLPort, readDouble==infinity at the end; with microsoft's STL, readDouble == 0.0.
  • Has this prototype any kind of meaning :) ?

Here is the prototype:

#include <float.h>
#include <limits>
#include <math.h>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
int main(int argc, const char* argv[]) {
  std::ostringstream os;
  //int digit10=std::numeric_limits<double>::digits10; // ==15
  //int digit=std::numeric_limits<double>::digits; // ==53
  os << std::setprecision(17);
  os << DBL_MAX;
  std::cout << os.str();
  std::stringbuf sb(os.str());
  std::istream is(&sb);
  double readDouble=0.0;
  is >> readDouble;
  bool success = fabs(DBL_MAX-readDouble)<0.1;
}
like image 874
sthiers Avatar asked Apr 14 '09 13:04

sthiers


2 Answers

numeric_limits::digits10 is the number of decimal digits that can be held without loss.

For example numeric_limits<unsigned char>::digits10 is 2. This means that an unsigned char can hold 0..99 without loss. If it were 3 it could hold 0..999, but as we all know it can only hold 0..255.

This manual page has an example for floating point numbers, which (when shortened) shows that

cout << numeric_limits<float>::digits10 <<endl;
float f = (float)99999999; // 8 digits
cout.precision ( 10 );
cout << "The float is; " << f << endl;

prints

6
The float is; 100000000
like image 130
Andrew Stein Avatar answered Oct 14 '22 06:10

Andrew Stein


numeric_limits::digits10 specifies the number of decimal digits to the left of the decimal point you can represent without a loss of precision. Each type will have a different number of representable decimal values.

like image 39
Aaron Saarela Avatar answered Oct 14 '22 06:10

Aaron Saarela