function pi(n) {
var sum = 0;
for (var k = 0; k < n; k++) {
sum = sum + Math.pow(-1, k) / (2 * k + 1);
}
return 4 * sum;
}
This function will estimate π with an accuracy related to
n
. Note that as n
increases, so does the time
to compute an estimate of π.
var piMemo = memoize(pi);
Here, the π-estimation function has been memoized to effect lazy
evaluation, so repeated executions for a given value of n
are fast, since the computation does not need to be redone.
Most of the interesting stuff is happening behind the scenes in JavaScript. Check out this page's source to dig into it.