How is pi (π) calculated?
In calculus there is a thing called Taylor Series which provides an easy way to calculate many irrational values to arbitrary precision.
Pi/4 = 1 - 1/3 + 1/5 - 1/7 + ...
(from http://www.math.hmc.edu/funfacts/ffiles/30001.1-3.shtml )
Keep adding those terms until the number of digits of precision you want stabilize.
Taylor's theorem is a powerful tool, but the derivation of this series using the theorem is beyond the scope of the question. It's standard first-year university calculus and is easily googlable if you're interested in more detail.
I didn't mean to imply that this is the most practical method to calculate pi. That would depend on why you really need to do it. For practical purposes, you should just copy as many digits as you need from one of the many published versions. I was suggesting this as a simple introduction of how irrational values can be equated to infinite series.
As an alternative to JeffH's method of storing every variation, you can just store the maximum number of digits and cut off what you don't need:
#include <string>
#include <iostream>
using std::cout; using std::endl; using std::string;
// The first 99 decimal digits taken from:
// http://www.geom.uiuc.edu/~huberty/math5337/groupe/digits.html
// Add more as needed.
const string pi =
"1415926535"
"8979323846"
"2643383279"
"5028841971"
"6939937510"
"5820974944"
"5923078164"
"0628620899"
"8628034825"
"342117067";
// A function in C++ that returns pi to X places
string CalcPi(const size_t decimalDigitsCount)
{
string returnValue = "3";
if (decimalDigitsCount > 0)
{
returnValue += "." + pi.substr(0, decimalDigitsCount);
}
return returnValue;
}
int main()
{
// Loop through all the values of "pi at x digits" that we have.
for (size_t i = 0; i <= pi.size(); ++i)
{
cout << "pi(" << i << "): " << CalcPi(i) << endl;
}
}
http://codepad.org/6mqDa1zj
Try "Computation of the n'th digit of pi in any base in O(n^2)". It's probably the fastest known algorithm that doesn't require arbitrary (read huge) precision floats, and can give you the result directly in base 10 (or any other).