The infinite series formula for calculating π is the following, according to Leibniz:
π/4 = 1/1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 ...
Meaning that if we multiply 4
by all the series it would result π, well, eventually.
π = 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + 4/13 ...
If we create an algoritm fast enough to support near infinite terms (it's impossible I know) we will have the best π approximation. The following is a simple approach to calculate π through the inifinte series approach.
function calculatePiByInfiniteSeries(numTerms) {
let pi = 1;
let sign = -1;
for(let odd = 3; odd < numTerms; odd += 2) {
pi += sign / odd;
sign *= -1;
}
return 4 * pi;
}
A function to measure time execution was also created to measure how much this algorithm take to calcualte a π approximation.
function measureExecSeconds(f) {
const firstDate = new Date();
const result = f();
const secondDate = new Date();
const diff = secondDate - firstDate;
const diffSeconds = diff / 1000
return [`${diffSeconds} seconds`, result];
}
The implementation of these two functions would be the following:
console.log( measureExecSeconds(() => calculatePiByInfiniteSeries(1000000)) )
To generate the results in time and aproximation the following implementation was created:
[
Math.pow(10, 6),
Math.pow(10, 7),
Math.pow(10, 8),
Math.pow(10, 9),
Math.pow(10, 10),
Math.pow(10, 11),
Math.pow(10, 12),
].forEach(numTerms => {
console.log( measureExecSeconds(() => calculatePiByInfiniteSeries(numTerms)) )
});
The following are the results in time and approximation of the algorithm given different powers of 10.
Number of terms | Time | ~π |
---|---|---|
10^6 | 0.002 seconds | 3.141590653589692 |
10^7 | 0.009 seconds | 3.1415924535897797 |
10^8 | 0.075 seconds | 3.1415926335902506 |
10^9 | 0.62 seconds | 3.141592651589258 |
10^10 | 6.151 seconds | 3.141592653388201 |
10^11 | 65.402 seconds | 3.1415926535685275 |
10^12 | 655.923 seconds | 3.1415926535865184 |
3.14159265359