Known as the Madhava–Leibniz method of calculating Pi. Originally known as the Leibniz formula for calculating Pi, it was discovered that Indian mathmematician and astronomer Madhava of Sangamagrama (or perhaps his followers) had formalized this method of calculating Pi in the 14th-15th century. A naming improvement since Leibniz already has too many formulas named after him.
It's beautifully simple. 1 - 1/3 + 1/5 - 1/7 + 1/9... continued to infinity gets you 1/4th of Pi.
And it's very easy to write in code. Here it is using python:
quarterPi = 0
for i in range(0, 1000000):
numerator = 1 if i % 2 == 0 else -1
denominator = i * 2 + 1
quarterPi += numerator / denominator
print(quarterPi * 4)
If we run this code, we get 3.1415916535897743
, which is surprisingly close to Pi, accurate to the 6th decimal.
Infinite series can't really be calculated to completion using a computer, but that for i in range(0, 1000000):
line controls how many iterations you calculate for (currently 1 million).
If we crank it up to 100 million iterations we can really make our CPUs work:
3.1415926525880504
100 million iterations took 180 seconds on my computer, and it's now accurate to the 8th decimal. Now, what about if we only loop 100 times?
3.1315929035585537
Not very accurate. It took my computer less than half of a millisecond to compute 100 iterations.
It's incredible to think that mathematicians were able to come up with this formula in a time when they couldn't necessarily check the results by hand.
User /u/Another_moose came up with this one line version of the algorithm:
sum(-(i*8%16-4)/(i*2+1) for i in range(10**6))
Mathematics can really illustrate how powerful programming can be, often with very little effort. Code representing math often ends up being some of the most concise, maybe because these two fields of study share some deep parallels.