Reputation: 967
Couple of questions from below code:
a) What does std::numeric_limits::digits10 denote? b) If (a) represents max 10 digits double number re-presentable on a machine then we can keep getting more and more precision by just adding +1, +2 and then whats the maximum re-presentable double value on a machine? How can be display that? i.e what std::numeric_limits::digits10 + MaxN?
#include <iostream>
#include <iomanip>
#include <cmath>
#include <limits>
int main(void)
{
double d1 = 0.1;
double d2 = 0.2;
double d3 = d1 + d2;
std::cout << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << "Sum 0.1 + 0.2 = " << d3 << std::endl;
std::cout << std::setprecision(std::numeric_limits<long double>::digits10 + 2) << "Sum 0.1 + 0.2 = " << d3 << std::endl;
std::cout << std::setprecision(std::numeric_limits<long double>::digits10 + 3) << "Sum 0.1 + 0.2 = " << d3 << std::endl;
std::cout << std::setprecision(std::numeric_limits<long double>::digits10 + 4) << "Sum 0.1 + 0.2 = " << d3 << std::endl;
return 0;
}
Upvotes: 0
Views: 1169
Reputation: 153457
What does
std::numeric_limits::digits10 denote?
double
is typically 64-bits and can exactly represent about 264 different values.
Text like "0.1"
, "3.1415926535897932384626433832795"
, etc. has infinite possibilities.
Convert text to double
and then back to text, do we get the same text (round-tripping)? This will not work for all possible text.
Take a sub-set of text possibilities, say only those with up to N leading significant decimal digits and with a limited exponent range.
numeric_limits<double>::digits10
(e.g. 15) is that N that allow for all successful round-tripping.
What is the maximum precision representable value for a given double value on a machine?
Typical double
is encoded using base-2 and has a maximum precision of 53 significant binary digits.
can keep getting more and more precision by just adding ...
Select double
values, written in decimal, take more than N
significant digits to write exactly. I'd say up to about 754.
Writing a double
to numeric_limits<double>::max_digits10
(e.g. 17) significant decimal digits is sufficient to distinguish it from all other double
.
A quality double
to text function will certainly and correctly write at least max_digits10
decimal digits. Beyond that it is up to the implementation. To meet IEEE 754, I am certain the minimum is max_digits10 + 3
.
numeric_limits<double>::digits10
differs from numeric_limits<double>::max_digits10
because the double
encoding using base 2 differs from text as base 10. The double
values are not nicely distributed along base 10 values.
Upvotes: 1