Skip to content

Instantly share code, notes, and snippets.

@dehowell
Last active August 29, 2015 14:07
Show Gist options
  • Save dehowell/b856f546b9af6d40c839 to your computer and use it in GitHub Desktop.
Save dehowell/b856f546b9af6d40c839 to your computer and use it in GitHub Desktop.
Calculating Pi with Monte Carlo Methods

This is a demonstration of how to calculate π using Monte Carlo integration.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
position: relative;
}
form {
position: absolute;
top: 1px;
}
</style>
<body>
<form>
<span class="samples"></span> samples.<br/>
&#960; = <span class="estimate"></span><br/>
<button type="button" onclick="addSamples(1000);">Add 1000 more samples.</button>
</form>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 600;
var x = d3.scale.linear()
.domain([0, 1])
.range([0, 600]);
var y = d3.scale.linear()
.domain([0, 1])
.range([height, 0]);
var fill = d3.scale.ordinal()
.domain([true, false])
.range(["#3182bd", "#deebf7"]);
var chart = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(180)");
function generatePoint() {
var pt = {x: Math.random(), y: Math.random()};
pt.inside = Math.sqrt(Math.pow(pt.x, 2) + Math.pow(pt.y, 2)) <= 1.0;
return pt;
}
function estimatePi(samples) {
var inside = 0;
samples.forEach(function(pt) {
if (pt.inside) {
inside += 1;
}
});
return 4 * inside / samples.length;
}
function update(data) {
var points = chart.selectAll(".point").data(data),
estimateOfPi = estimatePi(data);
points.enter().append("circle")
.attr("class", "point")
.attr("cx", function(d) { return x(d.x); })
.attr("cy", function(d) { return y(d.y); })
.attr("fill", function(d) { return fill(d.inside); })
.attr("fill-opacity", 0.2)
.attr("r", 2);
points.transition()
.duration(500)
.attr("fill-opacity", 0.8);
d3.selectAll(".estimate").text(d3.format("0.5f")(estimateOfPi));
d3.selectAll(".samples").text(data.length);
}
var samples = [];
function addSamples(n) {
for (var i = 0; i < n; i++) {
samples.push(generatePoint());
}
update(samples);
}
addSamples(5000);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment