Reputation: 111
I'm beginning to teach myself C++ until my class starts in the fall. I was wondering if you might be able to help me come up with a better way to ask the user for the number of digits they want for the number pi, and then display it. My problem is that using pi = atan(1)*4 isn't precise past around 10 decimal places. Is there a better built in number that has pi to at least 20 decimal places? Here is what I have so far, thanks!
#include <iostream>
#include <string>
#include <iomanip>
#include <ios>
#include <sstream>
using namespace std;
using std::setprecision;
using std::streamsize;
int main()
{
double pi = atan(1)*4;
int input = 0;
while(true)
{
cout << "Please enter how many digits of PI you would like to see (Max 20): ";
cin >> input;
if(input > 0 && input <= 20)
{
break;
}
else
{
cout << "That's not a valid number! Try again." << endl;
}
}
streamsize prec = cout.precision();
cout << setprecision(input);
cout << "Here you go: " << pi <<endl;
system("pause");
}
Upvotes: 0
Views: 7470
Reputation: 129364
A double will have 53 bits of precision. Each bit gives about 1/3 of a decimal digit (log(10)/log(2) to be precise), which means that we get approximately 53/3 digits out of a double. That should give 17 digits (including the 3 at the beginning). It's plausible that atan(1)
isn't giving quite all the digits of pi/4 either (because atan
as well as any other trigonometric function is an approximation).
If you want many more digits than about 12-14 digits, you will need to use a "big number" library, and there are a number of "clever" ways to calculate the decimals of PI.
Upvotes: 0
Reputation: 9270
The easiest way to do this would probably just have a std::string
containing the digits that you want ("3.14159265358979323846264338327950288419"
), and then just print the first input
digits beyond the decimal point.
Upvotes: 14
Reputation: 3931
I would say that this is less of a C++ problem, and more of a math problem. There are several infinite series that converge to the true value of Pi very quickly. Have you looked at the Wikipedia article on this topic?
As for being precise to nine or ten digits, you may run into rounding issues using double
(especially with certain calculation methods). I would consider looking into an arbitrary-precision math library. I'm a big fan of MPFR, but I'm sure Boost has something analogous if that's more your thing (keep in mind that Boost is a C++ library, whereas MPFR is a C library [although you can, of course, use C code from C++]).
MPFR does have a C++ wrapper, but in general I don't enjoy using it as much as the C functions, since the last time I looked at it (admittedly, a while ago), it wasn't quite as feature-complete.
It's probably worth noting also that, since your goal is to learn C++, and not to learn how to efficiently approximate Pi, it might be preferrable to solve this problem by e.g. just retrieving the first n-digits from a hard-coded string instead, as Chris said.
Upvotes: 4