Calculate PI with BigNumber.js

results

source


var i = 0;
var el = document.querySelector("#indicator");

setInterval(function(){
    el.style.marginLeft=(100 * Math.sin(i+=0.01) + 100) + "px";
},10)

function syncCalc(){
    showResult(calcPi(2000));
}

function threadCalc(){
    var thread = new Thread(calcPi, "https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/4.0.0/bignumber.min.js");
    thread.once(2000).done(function(a){
        showResult(a);
    });
}

var resultElement = document.querySelector("#result");
function showResult(d){
    var element = document.createElement('p');
    element.textContent = d; 
    resultElement.appendChild(element);
}

function calcPi(n){
    BigNumber.config({ DECIMAL_PLACES: n + 10, ROUNDING_MODE: BigNumber.ROUND_DOWN });
    var rep = Math.ceil(Math.log2(n));
    var a = new BigNumber(1);
    var an;
    var b = new BigNumber(1).div(new BigNumber(2).sqrt());
    var t = new BigNumber(1 / 4);
    var p = new BigNumber(1);
    
    console.time();
    for(i = 0; i < rep; i++){
        an = a.add(b).div(2);
        b = a.mul(b).sqrt();
        t = t.sub(p.mul(a.sub(an).pow(2)));
        p = p.mul(2);
        a = an;
    }
    console.timeEnd();
    return a.add(b).pow(2).div(t.times(4)).toString().slice(0,n+2);
}