I've been playing around with algorithms for computing pi. One that I noticed is the leibniz algorithm.
It states that pi can be approximated like this
$n = 1$ (The first odd number)
$$\pi = 4 \left(\frac{1}{n} - \frac{1}{n+2} + \frac{1}{n+4} - \frac{1}{n+6} + \cdots \pm \frac{1}{n + x} \right)$$
The nature of this algorithm is to start with the first odd number 1. Add 1 divided by that odd number, then subtract 1 divided by the next odd number. Flip the signs on every iteration. Finally, multiply this result by 4.
I created an algorithm for this in JavaScript.
function leibnez(n) {
var fraction = 0;
var denominator = 1;
var sign = "+";
for (var i = 1; i <= n; i++) {
sign = i % 2 == 0 ? "-" : "+";
if (sign == "+") {
fraction += (1 / denominator);
}
else {
fraction -= (1 / denominator);
}
denominator += 2;
}
return fraction * 4;
}
When calling leibniz(10000) which will perform 10000 such fractional additions/subtractions, I get a value of 3.14149 which is accurate only to 4 decimal places.
Calling leibniz(100000) results in a value of 3.14158 which is accurate only to 5 decimal places.
Is this algorithm really that inefficient at approximating pi or is the discrepency an error in JavaScript's floating point addition.
Due to conditional convergence, the error term is comparable to the last term of the series:
$$\pi=4 \left[ 1-\frac{1}{3}+\ldots+\frac{(-1)^{n-1}}{2n-1} \right]+(-1)^{n} \left( \frac{1}{n}-\frac{1}{4n^{3}}+\ldots+\frac{E_{2k}}{2^{2k}n^{2k+1}} +\ldots \right)$$
Modern calculations
BBP algorithm $$\pi =\sum_{n=0}^{\infty} \frac{1}{16^{n}} \left( \frac{4}{8n+1}-\frac{2}{8n+4}-\frac{1}{8n+5}-\frac{1}{8n+6} \right)$$
Ramanujan series
$$\frac{1}{\pi} = \frac{\sqrt{8}}{9801} \sum_{n=0}^{\infty} \frac{(4n)!}{(n!)^{4}} \frac{(1103+26390n)}{396^{4n}}$$
See also Borwein's algorithms for further interests.