Pi Estimator
Illustration of the "dart-throwing" pi estimator.
HTML
<input type="button" value="go" id="go">
<div id="value"></div>
JavaScript
/*
* Does a running approximation of pi by the famous dart throwing
* algorithm. Generates 1000 batches of 1000 random points, with
* a 20ms delay between batches. Displays the running results in
* the HTML element with id "value".
*/
document.getElementById("go").onclick = function nextBatch() {
var display = document.getElementById("value");
var totalPoints = 0;
var insidePoints = 0;
var nextBatch = function() {
for (var i = 0; i < 1000000000000; i += 1) {
var x = Math.random() * 2 - 1;
var y = Math.random() * 2 - 1;
if (x * x + y * y < 1) {
insidePoints += 1;
}
totalPoints += 1;
}
value.innerHTML = 4 * (insidePoints / totalPoints);
if (totalPoints > 100) {
return;
}
setTimeout(nextBatch, 1);
};
nextBatch();
};