calculate pi in csharp

There are many algorithms to calculate pi, one of the most well-known is the Leibniz formula:

main.cs
pi/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ...
46 chars
2 lines

The more terms you use, the closer you get to pi. Here is the C# code to calculate pi using this method:

main.cs
double pi = 0.0;
double sign = 1.0;
for (int i = 0; i < 1000000; i++)
{
    double term = sign / (2.0 * i + 1.0);
    pi += term;
    sign *= -1.0;
}
pi *= 4.0;
Console.WriteLine(pi);
184 chars
11 lines

This code uses a for loop to calculate the sum of the series with one million terms. The variable sign keeps track of whether the term is positive or negative, and it is multiplied by -1 at the end of each iteration to alternate signs. Finally, the result is multiplied by 4 to get pi.

Note that this algorithm converges very slowly to pi, so you may need to use millions or even billions of terms to get a good approximation. Other algorithms, such as the Gauss-Legendre algorithm or the Brent-Salamin algorithm, converge much faster but are more complicated to implement.

gistlibby LogSnag