Reputation: 2063
I've written a program to estimate pi using the Gregory Leibniz formula, however, it will not calculate to 18 decimal points. It will only calculate up to 5 decimal points. Any suggestions?
Upvotes: 1
Views: 428
Reputation: 41932
The default printing precision for printf
is 6
Precision specifies the exact number of digits to appear after the decimal point character. The default precision is 6
Similarly when std::cout
was introduced into C++ the same default value was used
Manages the precision (i.e. how many digits are generated) of floating point output performed by
std::num_put::do_put
.
- Returns the current precision.
- Sets the precision to the given one. Returns the previous precision.
The default precision, as established by
std::basic_ios::init
, is 6.
Therefore regardless of how precise the type is, only 6 fractional digits will be printed out. To get more digits you'll need to use std::setprecision
or std::cout.precision
However calling std::cout.precision
only affects the number of decimal digits in the output, not the number's real precision. Any digits over that type's precision would be just garbage
Most modern systems use IEEE-754 where float
is single-precision with 23 bits of mantissa and double
maps to double-precision with 52 bits of mantissa. As a result they're accurate to ~6-7 digits and ~15-16 decimal digits respectively. That means they can't represent numbers to 18 decimal points as you expected
On some platforms there may be some extended precision types so you'll be able to store numbers more precisely. For example long double
on most compilers on x86 has 64 bits of precision and can represent ~18 significant digits, but it's not 18 digits after the decimal point. Higher precision can be obtained with quadruple-precision on some compilers. To achieve even more precision, the only way is to use a big number library or write one for your own.
Upvotes: 0
Reputation: 26326
Use
cout.precision(50);
To increase the precision of the printed output. Here 50 is the number of decimal digits in your output.
Upvotes: 4