compute pi in csharp

Here is one way to compute pi in C# using the Leibniz formula:

main.cs
double ComputePi(int iterations)
{
    double pi = 0;
    for (int i = 0; i < iterations; i++)
    {
        double numerator = Math.Pow(-1, i);
        double denominator = (2 * i) + 1;
        pi += numerator / denominator;
    }
    pi *= 4;
    return pi;
}
262 chars
13 lines

The ComputePi method takes an int argument iterations, which specifies the number of iterations to use in the computation. The more iterations, the more accurate the result (but also the slower the computation).

The method uses the Leibniz formula to compute pi. The formula states that:

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

So, we can compute pi by summing the series up to a certain number of terms. We alternate adding and subtracting fractions of the form 1/(2n + 1), where n is the iteration index.

After computing the sum, we multiply it by 4 to get the value of pi.

Here's how you can call the method to compute pi to 10,000 terms:

main.cs
double pi = ComputePi(10000);
Console.WriteLine(pi);
53 chars
3 lines

gistlibby LogSnag