How is pi (π) calculated?

2020-02-02 17:38发布

How can I write a function which will return pi (π) to a given number of decimal places?

Speed is not a concern. I've been looking at http://bellard.org/pi/, but I still don't understand how to get the nth digit of pi.

9条回答
贪生不怕死
2楼-- · 2020-02-02 18:21

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.

查看更多
看我几分像从前
3楼-- · 2020-02-02 18:27

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).

查看更多
唯我独甜
4楼-- · 2020-02-02 18:30

Are you willing to look up values instead of computing them?

Since you didn't explicitly specify that your function has to calculate values, here's a possible solution if you are willing to have an upper limit on the number of digits it can "calculate":

// Initialize pis as far out as you want. 
// There are lots of places you can look up pi out to a specific # of digits.
double pis[] = {3.0, 3.1, 3.14, 3.141, 3.1416}; 

/* 
 * A function that returns pi out to a number of digits (up to a point)
 */
double CalcPi(int x)
{
    // NOTE: Should add range checking here. For now, do not access past end of pis[]
    return pis[x]; 
}

int main()
{
    // Loop through all the values of "pi at x digits" that we have.
    for (int ii=0; ii<(int)sizeof(pis)/sizeof(double); ii++)
    {
        double piAtXdigits = CalcPi(ii);
    }
}

Writing CalcPi() this way (if it meets your needs) has a side benefit of being equally screaming fast for any value of X within your upper limit.

查看更多
登录 后发表回答