Compute PI with Monte Carlo
by gamealchemist
HTML
<canvas id='cv' width=400 height=400></canvas>
<div id='pi'></div>
<div id='piAcc'></div>
<div id='pntCnt'></div>
<div id='time'></div>
JavaScript
// Parameters
var displayWhileComputing = true;
var batchSize = 1000;
var batchCount = 10000;
var usePostMessage = false;
// BoilerPlate
var $ = document.getElementById.bind(document);
var cv = $('cv');
var ctx = cv.getContext('2d');
var piDiv = $('pi');
var piAccDiv = $('piAcc');
var pntCntDiv = $('pntCnt');
var timeDiv = $('time');
// Canvas setup
ctx.translate(200, 200);
ctx.scale(200, 200);
ctx.globalAlpha = 0.05;
var pixelSize = 1 / 200;
// Computing vars
var pointInsideCount = 0;
var pointCount = 0;
var piApproximation = 0;
var accuracy = 0;
var shouldStop = false;
var postpone = (function () {
var fnMap = new Map(), idMap = new Map(), fnId = 0;
var msg = { fnId: 0 };
function _postpone(fn) {
if (!fnMap[fn]) {
fnId++;
fnMap[fn] = fnId;
idMap[fnId] = fn;
}
msg.fnId = fnMap[fn];
postMessage(msg, '*');
}
function _postponeListener(e) {
var fnId = e.data.fnId;
if (fnId) idMap[fnId]();
}
window.addEventListener("message", _postponeListener);
return _postpone;
}());
var blue = '#00F';
var red = '#F00';
var resumeFunction = usePostMessage ? function () {
postpone(resumeCompute);
} : function () {
setTimeout(resumeCompute, 0);
};
function monteCarlo() {
for (var i = 0; i < batchSize; i++) {
var x = 1 - 2 * Math.random();
var y = 1 - 2 * Math.random();
pointCount++;
if ((x * x + y * y) <= 1) {
pointInsideCount++;
if (displayWhileComputing) {
ctx.fillStyle = blue;
ctx.fillRect(x, y, pixelSize, pixelSize);
}
} else {
if (displayWhileComputing) {
ctx.fillStyle = red;
ctx.fillRect(x, y, pixelSize, pixelSize);
}
}
}
piApproximation = 4 * pointInsideCount / pointCount;
accuracy = piApproximation / Math.PI;
if (displayWhileComputing) {
...