How do I calculate PI in C#?

2019-01-16 09:28发布

How can I calculate the value of PI using C#?

I was thinking it would be through a recursive function, if so, what would it look like and are there any math equations to back it up?

I'm not too fussy about performance, mainly how to go about it from a learning point of view.

标签: c# pi
21条回答
叼着烟拽天下
2楼-- · 2019-01-16 09:45

PI (π) can be calculated by using infinite series. Here are two examples:

Gregory-Leibniz Series:

π/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - ...

C# method :

public static decimal GregoryLeibnizGetPI(int n)
{
    decimal sum = 0;
    decimal temp = 0;
    for (int i = 0; i < n; i++)
    {
        temp = 4m / (1 + 2 * i);
        sum += i % 2 == 0 ? temp : -temp;
    }
    return sum;
}

Nilakantha Series:

π = 3 + 4 / (2x3x4) - 4 / (4x5x6) + 4 / (6x7x8) - 4 / (8x9x10) + ...

C# method:

public static decimal NilakanthaGetPI(int n)
{
    decimal sum = 0;
    decimal temp = 0;
    decimal a = 2, b = 3, c = 4;
    for (int i = 0; i < n; i++)
    {
        temp = 4 / (a * b * c);
        sum += i % 2 == 0 ? temp : -temp;
        a += 2; b += 2; c += 2;
    }
    return 3 + sum;
}

The input parameter n for both functions represents the number of iteration.

The Nilakantha Series in comparison with Gregory-Leibniz Series converges more quickly. The methods can be tested with the following code:

static void Main(string[] args)
{
    const decimal pi = 3.1415926535897932384626433832m;
    Console.WriteLine($"PI = {pi}");

    //Nilakantha Series
    int iterationsN = 100;
    decimal nilakanthaPI = NilakanthaGetPI(iterationsN);
    decimal CalcErrorNilakantha = pi - nilakanthaPI;
    Console.WriteLine($"\nNilakantha Series -> PI = {nilakanthaPI}");
    Console.WriteLine($"Calculation error = {CalcErrorNilakantha}");
    int numDecNilakantha = pi.ToString().Zip(nilakanthaPI.ToString(), (x, y) => x == y).TakeWhile(x => x).Count() - 2;
    Console.WriteLine($"Number of correct decimals = {numDecNilakantha}");
    Console.WriteLine($"Number of iterations = {iterationsN}");

    //Gregory-Leibniz Series
    int iterationsGL = 1000000;
    decimal GregoryLeibnizPI = GregoryLeibnizGetPI(iterationsGL);
    decimal CalcErrorGregoryLeibniz = pi - GregoryLeibnizPI;
    Console.WriteLine($"\nGregory-Leibniz Series -> PI = {GregoryLeibnizPI}");
    Console.WriteLine($"Calculation error = {CalcErrorGregoryLeibniz}");
    int numDecGregoryLeibniz = pi.ToString().Zip(GregoryLeibnizPI.ToString(), (x, y) => x == y).TakeWhile(x => x).Count() - 2;
    Console.WriteLine($"Number of correct decimals = {numDecGregoryLeibniz}");
    Console.WriteLine($"Number of iterations = {iterationsGL}");

    Console.ReadKey();
}

The following output shows that Nilakantha Series returns six correct decimals of PI with one hundred iterations whereas Gregory-Leibniz Series returns five correct decimals of PI with one million iterations:

enter image description here

My code can be tested >> here

查看更多
趁早两清
3楼-- · 2019-01-16 09:48
public double PI = 22.0 / 7.0;
查看更多
我想做一个坏孩纸
4楼-- · 2019-01-16 09:51

In any production scenario, I would compel you to look up the value, to the desired number of decimal points, and store it as a 'const' somewhere your classes can get to it.

(unless you're writing scientific 'Pi' specific software...)

查看更多
孤傲高冷的网名
5楼-- · 2019-01-16 09:52

If you want recursion:

PI = 2 * (1 + 1/3 * (1 + 2/5 * (1 + 3/7 * (...))))

This would become, after some rewriting:

PI = 2 * F(1);

with F(i):

double F (int i) {
    return 1 + i / (2.0 * i + 1) * F(i + 1);
}

Isaac Newton (you may have heard of him before ;) ) came up with this trick. Note that I left out the end condition, to keep it simple. In real life, you kind of need one.

查看更多
乱世女痞
6楼-- · 2019-01-16 09:56

First, note that C# can use the Math.PI field of the .NET framework:

https://msdn.microsoft.com/en-us/library/system.math.pi(v=vs.110).aspx

The nice feature here is that it's a full-precision double that you can either use, or compare with computed results. The tabs at that URL have similar constants for C++, F# and Visual Basic.

To calculate more places, you can write your own extended-precision code. One that is quick to code and reasonably fast and easy to program is:

Pi = 4 * [4 * arctan (1/5) - arctan (1/239)]

This formula and many others, including some that converge at amazingly fast rates, such as 50 digits per term, are at Wolfram:

Wolfram Pi Formulas

查看更多
唯我独甜
7楼-- · 2019-01-16 09:58

Here is an article on Calculating PI in C#:

http://www.boyet.com/Articles/PiCalculator.html

查看更多
登录 后发表回答