# Srinivasa Ramanujan's expansion of Pi

Many years ago I created a small silverlight “applet” that was able to calculate Pi based on some famous expansions. With continued fractions it is also possible to arrive at the value of Pi, but the expansions that converge the fastest are the ones discovered by Srinivasa Ramanujan. The wikipedia page on Pi expansions talks about them here.

$\frac{1}{\pi} = \frac{2\sqrt{2}}{9801}\displaystyle\sum_{k=0}^\infty\frac{(4k)!(1103+26390k)}{(k!)^4 396^{4k}}$

Of course the function is writable in Typescript (follow this link to a ts playground to try it out.). Here’s the code:

```
interface Factorial { (n: number): number; cache: Record<number, number>; }
const factorial : Factorial = function(n: number): number {
if (n == 0) return 1;
if (factorial.cache[n]) return factorial.cache[n];
factorial.cache[n] = n * factorial(n-1);
return factorial.cache[n];
};
factorial.cache = {};
function calculatePi(n : number) {
let sum = 0;
for (let i = 0; i <= n; i++) {
let numerator = factorial(4*i) * (1103 + 26390 * i);
let denominator = Math.pow(factorial(i), 4) * Math.pow(396, 4 * i);
sum += numerator / denominator;
}
return 1 / (2 * Math.sqrt(2) / 9801 * sum);
}
console.log(calculatePi(0));
```

The only problem is…Srinivasa’s expansion converges so fast that after 2 iterations the accuracy of javascript’s number type is already exhausted. Great work, Sir!