Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active February 9, 2016 01:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbostock/31bd072e50eaf550d79e to your computer and use it in GitHub Desktop.
Save mbostock/31bd072e50eaf550d79e to your computer and use it in GitHub Desktop.
Annulus Sampling I
license: gpl-3.0

This animation demonstrates the perils of naïve annulus sampling. If the radius and angle are chosen with random uniformity, the sample density will be higher where the radius is smaller, and thus points will be concentrated around the inner edge of the annulus. See corrected sampling.

<!DOCTYPE html>
<meta charset="utf-8">
<canvas width="960" height="500"></canvas>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var canvas = d3.select("canvas"),
canvasNode = canvas.node(),
context = canvasNode.getContext("2d");
var numSamplesPerFrame = 50,
numSamples = 0;
var width = canvasNode.width,
height = canvasNode.height,
outerRadius = (Math.min(width, height) - 5) / 2,
innerRadius = outerRadius / 4;
context.translate(width / 2, height / 2);
context.save();
context.beginPath();
context.arc(0, 0, outerRadius, 0, 2 * Math.PI);
context.moveTo(innerRadius, 0);
context.arc(0, 0, innerRadius, 2 * Math.PI, 0);
context.fillStyle = "rgba(0,0,0,.2)";
context.fill("evenodd");
context.restore();
context.fillStyle = "rgba(0,0,0,.5)";
d3.timer(function() {
for (var i = 0; i < numSamplesPerFrame; ++i) {
var r = innerRadius + Math.random() * (outerRadius - innerRadius),
a = Math.random() * 2 * Math.PI,
x = r * Math.cos(a),
y = r * Math.sin(a);
context.beginPath();
context.arc(x, y, 1, 0, 2 * Math.PI);
context.fill();
}
return ++numSamples > 1000;
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment