So I've gotten the answer to my last question (I don't know why I didn't think of that). I was printing a double
using cout
that got rounded when I wasn't expecting it. How can I make cout
print a double
using full precision?
You can set the precision directly on std::cout
and use the std::fixed
format specifier.
double d = 3.14159265358979;
cout.precision(17);
cout << "Pi: " << fixed << d << endl;
You can #include <limits>
to get the maximum precision of a float or double.
#include <limits>
typedef std::numeric_limits< double > dbl;
double d = 3.14159265358979;
cout.precision(dbl::max_digits10);
cout << "Pi: " << d << endl;
Why do you explicitly advise to use
fixed
? Withdouble h = 6.62606957e-34;
,fixed
gives me0.000000000000000
andscientific
outputs6.626069570000000e-34
.The precision needs to be 17 (or std::numeric_limits<double>::digits10 + 2) because 2 extra digits are needed when converting from decimal back to the binary representation to ensure the value is rounded to the same original value. Here is a paper with some details: docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
Is the really the right answer? When I manually use a high number, I can print out as many as 51 digits of approximated e, but with
cout.precision(numeric_limits<double>::digits10 + 2);
I only get 16....For those looking where it mentions 17 digits in the paper @MikeFisher cited, it's under Theorem 15.
@MikeFisher You're right, C++11 introduces
max_digits10
to denote the same. Fixed the answer to reflect this.