Calculating Pi in JavaScript using Gregory-Leibniz Series
You may also do as follows; The function will iterate 10M times and will return you PI with n
significant digits after the decimal point.
function getPI(n){
var i = 1,
p = 0;
while (i < 50000000){
p += 1/i - 1/(i+2);
i += 4;
}
return +(4*p).toFixed(n);
}
var myPI = getPI(10);
console.log("myPI @n:100M:", myPI);
console.log("Math.PI :", Math.PI);
console.log("The Diff :", Math.PI-myPI);
You could use an increment of 4 and multiply at the end of the function with 4
.
n
is not the number of digits, but the counter of the value of the series.
function pi(n) {
var v = 0;
for (i = 1; i <= n; i += 4) { // increment by 4
v += 1 / i - 1 / (i + 2); // add the value of the series
}
return 4 * v; // apply the factor at last
}
console.log(pi(1000000000));