In honor of Pi day (3/14) and my increased fascination with mathematics as a whole, I decided to look under the hood and understand how the value of pi is calculated to be 3.14159… and write a program to do it.
Introducing: Pi-Py. Keep reading to learn more about the underlying process!
As it turns out, there are a number of approaches mathematicians have taken. For now, I chose to work with two methods: the Gregory-Leibniz series and the Nilakantha series. Here’s how they work.
Gregory-Leibniz
This method can accurately calculate to 5 decimal places after approximately 450,000 iterations. That’s a lot!
Using sigma notation:
This is basically fancy notation for a loop – a summation.
In this case, is the initial value, is the number of iterations, and is the body of the loop.
Another way of representing this, which is perhaps easier to understand more directly, is as follows:
(Note: I multiplied each number by 4 to get the value of rather than )
This can be easily computed in a loop by alternating addition and subtraction of odd numbers. View the code on GitHub to see how this was implemented!
Nilakantha
This method is considerably faster – by about 10,000 times, as a matter of fact. After only 45 iterations, can be calculated to the same 5 decimal places as the Gregory-Leibniz method.
In the 15th Century, Indian astronomer/mathematician Nilakantha Somayaji published the following infinite series:
As the denominator value changes incrementally, this too can be easily computed using a simple loop.
View the code on GitHub to see how I implemented the Nilakantha infinite series!
The Nilakantha method converges at a much faster rate than the Gregory-Leibniz method, but there are even faster series which I have not yet studied or attempted to implement as life has kept me busy! Nevertheless, it has been an interesting journey, and I’ll be posting about other projects soon.
As a side-note, I had the chance to learn some LaTeX syntax as a result of writing this article, which really helped to make the material look presentable.