Last active
August 29, 2015 14:16
-
-
Save 1995eaton/14b2803f9675a3c123c6 to your computer and use it in GitHub Desktop.
Monte Carlo Pi Approximation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<title>Monte Carlo Pi Approximation</title> | |
<meta name="description" content=""> | |
<meta name="author" content=""> | |
<style> | |
html, body { | |
font-family: Helvetica, 'Helvetica Neue', Neue, sans-serif, Arial; | |
} | |
* { | |
box-sizing: border-box; | |
} | |
#canvas { | |
border: 1px solid; | |
} | |
input { | |
max-width: 75px; | |
} | |
</style> | |
</head> | |
<body> | |
<canvas id="canvas"></canvas> | |
<div id="approximation"></div> | |
<div id="config"> | |
<form onsubmit="redraw(); return false;"> | |
Grid width: <input type="number" id="width" min="0"> | |
Accuracy: <input type="number" id="accuracy" min="0"> | |
<input type="submit" value="redraw"> | |
<form> | |
</div> | |
</body> | |
<script> | |
var monteCarlo = (function() { | |
var canvas = document.getElementById('canvas'), | |
context = canvas.getContext('2d'); | |
return function(radius, trials, targetWidth) { | |
canvas.width = canvas.height = radius; | |
radius -= targetWidth - 1; | |
if (innerWidth > innerHeight && radius > innerHeight) { | |
canvas.style.height = innerHeight * 5 / 6 + 'px'; | |
} else if (innerHeight > innerWidth && radius > innerWidth) { | |
canvas.style.height = innerWidth * 5 / 6 + 'px'; | |
} | |
for (var i = 0, h = 0, x, y; i < trials; ++i) { | |
x = ~~(Math.random() * radius); | |
y = ~~(Math.random() * radius); | |
if (Math.sqrt(x * x + y * y) < radius) { | |
context.fillStyle = 'blue'; | |
++h; | |
} else { | |
context.fillStyle = 'red'; | |
} | |
context.fillRect(x, radius - y - 1, targetWidth, targetWidth); | |
} | |
var piApprox = h / trials * 4; | |
document.getElementById('approximation').textContent = | |
'pi ≈ ' + piApprox + ', error = ' + | |
(Math.abs(Math.PI - piApprox) / piApprox * 100).toFixed(4) + '%'; | |
}; | |
})(); | |
(function() { | |
var N = ~~(Math.min(1500, innerWidth, innerHeight) * 5 / 6); | |
var A = (N * N) >> 3; | |
var widthElement = document.getElementById('width'); | |
var accuracyElement = document.getElementById('accuracy'); | |
widthElement.value = N; | |
accuracyElement.value = A; | |
monteCarlo(N, A, 2); | |
window.redraw = function() { | |
monteCarlo(~~widthElement.value || 500, | |
~~accuracyElement.value || 10000, | |
2); | |
}; | |
})(); | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment