o9s
is a microblog
home archives search feed blogroll


Calculating PI

In honor of PI day.

Leibniz formula for π

Leibniz formula for PI

let s = 0;
let signToggle = true;

for (let x = 3; x < 10000; x += 2) {
    if (signToggle) {
    s += 1 / x;
    signToggle = false;
  } else {
    s -= 1 / x;
    signToggle = true;
  }
}

pi = (1 - s) * 4;

console.log(pi); // 3.14139265359179

Same code shortened.

for(var pi=0,x=3,s=-1;x<10000;pi+=(s*=-1)/x,x+=2);
console.log(((1 - pi) * 4)); // 3.14139265359179

It’s not very accurate, it’s wrong after only 4 decimals.

Bailey–Borwein–Plouffe formula

Bailey-Borwein-Plouffe formula

for(var pi=0,k=0;k<88;pi+=1/Math.pow(16,k/8)*(4/(k+1)-2/(k+4)-1/(k+5)-1/(k+6)),k+=8);
console.log(pi); // 3.141592653589793

Viète’s formula

Viete formula

let numerator = Math.sqrt(2);
let fraction = numerator / 2;
let twoOverPI = fraction;

for (let i = 0; i < 10000; i++) {
    numerator = Math.sqrt(2 + numerator);
  fraction = numerator / 2;
    twoOverPI *= fraction;
}

let pi = 2 / twoOverPI;
console.log(pi); // 3.141592653589794

Same code shortened.

for (var i=0,pi=1,num=0;i<1000;pi*=(num=Math.sqrt(2+num))/2,i++);console.log(2/pi);
console.log(pi); // 3.141592653589794

Credits to MSC for the Bailey-Borwein-Plouffe algorithm and the shortened versions.

Posted on 2018-03-14   #javascript     #node  






← Next post    ·    Previous post →