There are many algorithms to calculate pi, one of the most well-known is the Leibniz formula:
main.cs46 chars2 lines
The more terms you use, the closer you get to pi. Here is the C# code to calculate pi using this method:
main.cs184 chars11 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