So let’s take a look at what I reckon would be the harder of the two: the derivation of π.
π – the number… not the tasty baked good.
So, when it came to doing this, I did a little research into the various formulae that have been used to calculate π. I came across this little tidbit from Madhava of Sangamagrama:
This is an infinite series that rapidly converges to the value of π, and Madhava was from the 14th century… And using the square root of 12… Who would have thought of this back then..?
If you recall from two posts ago I had created a square root function, so this part is easy… I’ve also dealt with cumulative sums before in my previous post with the derivations of the non-native sine and cosine functions, and I’ve also created an integer power function as well. So technically, we have all the ingredients to make some delicious “π” (pun intended)…
So let’s take a look at building this up. Let’s grab the two main functions we need to make this happen, the square root function and the power functions:
These two functions were discussed in previous posts. The integer power function p(x,y) raises a positive integer, x, to the power of another positive integer, y. Whereas the square root function r(x), takes a number, x, and runs Newton’s Method of Approximation for square roots until zero underflow is reached in order to provide the square root.
Using these two functions we’ll put together a pi() function that uses these two and one other function (the cumulative sum function) that we’ll create right now:
The results will surprise you:
pi() gives 3.141592653589794
Math.PI gives 3.141592653589793
e – the number… I’ve got nothing to compare this against, so let’s just get on with it…
Okay, this is far simpler… e is defined as the cumulative sum of the reciprocals of all natural integer factorials from zero and above… In other words:
It’s interesting to note that as 0! and 1! are both equal to 1, the first two terms of this series make up about 73.5% of the total value of e… Just thought I’d randomly share that bit of trivia there…
Anyhow… If we create a similar cumulative function called e() which adds the reciprocal of reach natural integer factorial, borrowing our factorial function from my post a few weeks ago:
…we then have our function… 100 iterations would once again be sufficient to get to our value within acceptable accuracy… Put to the test:
e(99) gives 2.7182818284590455
Math.E() gives 2.718281828459045
WolframAlpha shows e as continuing after the 2845 with 904523, so apart from that last digit in the return value from our function, it’s practically identical and with a surprising amount of accuracy!
So there we have it… We’ve succeeded in deriving two irrational numbers using a few fundamental functions through basic operators, recursion and fat arrow functions.