开发者

Trying to calculate Pi to N number of decimals with C#

Note: I've already read this topic, but I don't understand it an开发者_如何学Pythond it doesn't provide a solution I could use. I'm terrible with number problems.

What's a simple way to generate Pi to what number of decimals a user wants? This isn't for homework, just trying to complete some of the projects listed here:

Link


A classic algorithm for calculating digits of pi is the Gauss-Legendre algorithm. While it is not as fast as some of the more modern algorithms it does have the advantage of being understandable.

Let

a_0 = 1
b_0 = 1/Sqrt(2)
t_0 = 1/4
p_0 = 1

Then

a_(n+1) = (a_n + b_n) / 2
b_(n+1) = Sqrt(a_n * b_n)
t_(n+1) = t_n - p_n * (a_n - a_(n+1))^2
p_(n+1) = 2 * p_n

Then

pi =. (a_n + b_n)^2 / (4 * t_n)

Here (=. means "approximately equal to") This algorithm exhibits quadratic convergence (the number of correct decimal places doubles with each iteration).

I'll leave it to you to translate this to C# including discovering an arbitrary-precision arithmetic library.


The topic your talking about calculate the value of PI using the taylor series. Using the function "double F (int i)" wrote on that topic will give you the value of PI after "i" terms.

This way of calculating PI is kind of slow, i suggest you to look at the PI fast algorithm.

You can also find one implementation here that get the calculate PI to the n th digit.

Good luck!


If you take a close look into this really good guide:

Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4

You'll find at Page 70 this cute implementation (with minor changes from my side):

static decimal ParallelPartitionerPi(int steps)
{
    decimal sum = 0.0;
    decimal step = 1.0 / (decimal)steps;
    object obj = new object();
    Parallel.ForEach(Partitioner.Create(0, steps),
        () => 0.0,
        (range, state, partial) =>
            {
                for (int i = range.Item1; i < range.Item2; i++)
            {
                decimal x = (i + 0.5) * step;
                partial += 4.0 / (1.0 + x * x);
            }
            return partial;
        },
        partial => { lock (obj) sum += partial; });
    return step * sum;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜