Monte-Carlo test to determine Pi

by Anton

HTML

<h3>Monte-Carlo calculating &Pi;</h3>

<p>
    Iterations: <span id="iter">0</span><br/>
    &Pi; = <span id="pi">…</span>
</p>

<button id="start">Start</button>

CSS

button {
    cursor: pointer;
}

JavaScript

var maxIter = 100000000;

var pi = 0,
    dotsIn = 0,
    currIter = 0,
    chunk = 1000000;

$('#start').click(function() {
    $('button').attr('disabled', 'disabled');
    
    pi = 0;
    dotsIn = 0;
    currIter = 0;
    
    calcChunk();
    
    //cron = setInterval(updateDisplay, 1000);
    //clearInterval(cron);
    
    $('#iter').text(numberWithCommas(maxIter));
    $('#pi').text(pi);
});

function calcChunk() {
    for(var i = 1; i <= chunk; i++) {
        if(nextDot())
            dotsIn++;
        
        pi = 4.0 * dotsIn / ++currIter;
    }
                             
    $('#iter').text(numberWithCommas(currIter));
    $('#pi').text(pi);
    
    if(currIter < maxIter)
        setTimeout(calcChunk, 10);
    else
        $('button').removeAttr('disabled');
}

function nextDot() {
    var x = Math.random();
    var y = Math.random();
    var dist = Math.sqrt(x*x + y*y);
    
    // console.log(dist);
    
    return dist <= 1;
}

// http://stackoverflow.com/a/2901298/253974
function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}