Estimate PI using Monte Carlo Method
HTML
<div id="output"></div>
<canvas id="canvas" width="100" height="100"></canvas>
JavaScript
var w = 100;
var h = 100;
var cx = 50;
var cy = 50;
var r = 50;
var total = 0;
var inside = 0;
var estimate = 0;
var iterations = 10;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.strokeStyle = 'rgba(0,0,0,0.2)';
ctx.fillStyle = 'rgba(0,0,0,0.2)';
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2, false);
ctx.closePath();
ctx.stroke();
function update() {
var px, py, dx, dy, d;
for(var i = 0; i < iterations; i++) {
px = Math.random() * w;
py = Math.random() * h;
dx = px - cx;
dy = py - cy;
d = Math.sqrt(dx*dx + dy*dy);
total++;
if(d < r) {
ctx.fillStyle = 'rgba(0,255,0,0.2)';
inside++;
} else {
ctx.fillStyle = 'rgba(255,0,0,0.2)';
}
ctx.fillRect(px,py,1,1);
}
estimate = 4 * (inside / total);
$('#output').text('Estimate for Pi: ' + estimate.toFixed(4));
setTimeout(update, 1000 / 30);
}
update();