calculation of pi in csharp

Here's one way to calculate the value of pi in C# using the Leibniz formula:

main.cs
double pi = 0.0;
for (int i = 0; i < 1000000; i++)
{
    pi += Math.Pow(-1, i) / (2 * i + 1);
}
pi *= 4;

Console.WriteLine(pi);
129 chars
9 lines

This program uses a loop to add up the terms of the Leibniz formula, which alternates between positive and negative values. The denominator increases incrementally by 2 each time to add the next odd integer to the series. After adding up a sufficient number of terms, the value of pi is multiplied by 4 to calculate the final result.

Note that the program does not use the most efficient algorithm for calculating pi, but it is simple to implement and works well for small values of n. There are many other approaches and algorithms for calculating pi more accurately, such as the Gauss-Legendre algorithm, the Monte Carlo method, and the Borwein algorithm.

gistlibby LogSnag