Created
February 22, 2020 18:58
-
-
Save xkef/fbcdbf25afc190c7086d731cc00fed17 to your computer and use it in GitHub Desktop.
monte-carlo for π
This file contains hidden or 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> | |
<head> | |
<script src="https://d3js.org/d3.v3.min.js"></script> | |
<title>monte carlo</title> | |
</head> | |
<body> | |
<script> | |
var width = 800; | |
var height = 800; | |
var div = d3 | |
.select('body') | |
.append('div') | |
.style('opacity', 0); | |
var svg = d3 | |
.select('body') | |
.append('svg') | |
.attr('width', width) | |
.attr('height', height); | |
svg | |
.append('circle') | |
.attr('cx', width / 2) | |
.attr('cy', width / 2) | |
.attr('r', width / 2) | |
.attr('fill', 'grey') | |
.style('opacity', 0.8); | |
// defined range of unit circle | |
var range = [-width, width]; | |
var distribution_size = 10000; | |
var inside = 0; | |
function getRandPoint(min = range[0], max = range[1]) { | |
var x = Math.random() * (max - min) + min; | |
var y = Math.random() * (max - min) + min; | |
return { x, y }; | |
} | |
for (var i = 0; i < distribution_size; i++) { | |
var { x, y } = getRandPoint(); | |
var isInside = x ** 2 + y ** 2 < width ** 2; | |
if (isInside) inside++; | |
svg | |
.append('circle') | |
.attr('cx', x) | |
.attr('cy', y) | |
.attr('r', 2) | |
.style('fill', 'black'); | |
} | |
console.log({ distribution_size, inside }); | |
console.log('pi = ', (4 * inside) / distribution_size); | |
var foot = document.createElement('footer'); | |
var footertext = 'π = ' + `${(4 * inside) / distribution_size}`; | |
foot.innerHTML = footertext; | |
foot.style = 'text-indent: 370px; font-size: 24px;'; | |
document.body.appendChild(foot); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment