Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

c++ - What is the meaning of numeric_limits<double>::digits10

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...