What is the meaning of numeric_limits::digits10

后端 未结 5 983
灰色年华
灰色年华 2020-11-29 07:46

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

相关标签:
5条回答
  • 2020-11-29 08:04

    See this very readable paper: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2005.pdf

    Although DBL_MAX ( = std::numeric_limits::digits10 = 15 digits) is the minimum guaranteed number of digits for a double, the DBL_MAXDIG10 value (= 17 digits) proposed in the paper has the useful properties:

    • Of being the minimum number of digits needed to survive a round-trip to string form and back and get the same double in the end.

    • Of being the minimum number of digits needed to convert the double to string form and show different strings every time you get (A != B) in code. With 16 or fewer digits, you can get doubles that are not equal in code, but when they are converted to string form they are the same (which will give the case where they are different when compared in the code, but a log file will show them as identical - very confusing and hard to debug!)

    When you compare values (e.g. by reviewing them manually by diff'ing two log files) we should remember that digits 1-15 are ALWAYS valid, but differences in the 16th and 17th digits MAY be junk.

    0 讨论(0)
  • 2020-11-29 08:07

    digits10 is for conversion: string → double → string
    max_digits10 is for conversion: double → string → double

    In your program, you are using the conversion (double → string → double). You should use max_digits10 instead of digits10.


    For more details about digits10 and max_digits10, you can read:

    • difference explained by stackoverflow
    • digits10
    • max_digits10
    0 讨论(0)
  • 2020-11-29 08:25

    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
    
    0 讨论(0)
  • 2020-11-29 08:29

    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.

    0 讨论(0)
  • 2020-11-29 08:29

    The '53' is the bit width of the significand that your type (double) holds. The '15' is the number of decimal digits that can be represented safely with that kind of precision.

    0 讨论(0)
提交回复
热议问题