PI in C# - 9/4/2016

So, in India in the late 14th century a very clever mathematician called Madhava of Sangamagrama figured out how to calculate the ratio between a circles diameter and it's radius aka Pi (Π). Called the Madhava–Leibniz series, it starts at 4 and adds and subtracts alternate ratios of 4 divided by the sequence of odd numbers starting at 3 e.g. 3, 5, 7, .... The more iterations done, the closer the value is to PI and depending on the accuracy needed, the iterations can be adjusted accordingly:

Pi = 4 - 4/3 + 4/5 - 4/7 + ...

See Wikipedia and the Story of Mathematics

To implement it in C# here is a code snippet

var myPi = 4.0;
for(int i=0; i< iterations; i++)
{
	double divisor = (i + 1) * 2 + 1;
	if(i %2 == 0)
	{
		myPi -= 4.0f / divisor;
	} else
	{
		myPi += 4.0f / divisor;
	}
}

Of interest is the large number of iterations to get a useful approximation of PI e.g. to 5 decimal places, see the table below:

Iterations Places correct Value
10,000,000 6 3.14159275358978
136,150 5 3.14159999837605
100,000 4 3.14160265348972

Download the entire code here

Blog ID: 2016 Blog_636085440000000000