Approximating Pi with Buffon's Needle

I’m a bit late for Pi Day, but Programming Praxis had a neat problem on Friday that I wanted to check out:

Suppose we have a floor made of parallel strips of wood, each the same width, and we drop a needle onto the floor. What is the probability that the needle will lie across a line between two strips?

It turns out (as you might have guessed from the title) that the probability ends up being equal to 2/pi. How can we show that? Well in this case, I have a nice JavaScript simulation for you (down at the end of the post). The code is actually really straight forward:

// Drop a bunch of needles
var x1, y1, theta, x2, y2;
for (var i = 0; i < numberToDrop; i++) {
	// Drop a new needle
	x1 = (Math.random() * (width - 2 * needleLength)) + needleLength;
	y1 = (Math.random() * (height - 2 * needleLength)) + needleLength;
	theta = Math.random() * 2 * Math.PI;

	x2 = x1 + needleLength * Math.cos(theta);
	y2 = y1 + needleLength * Math.sin(theta);

	// Check if it crosses a line
	// Yes, this isn't the best way to do this
	var crossesLine = false;
	for (var x = needleLength / 2; x <= canvas.width; x += needleLength) {
		if ((x1 <= x && x <= x2) || (x2 <= x && x <= x1))
			crossesLine = true;

	// Record the toss
	tossed += 1;
	if (crossesLine) crossed += 1;

console.log("pi ~ " + (2 * tossed / crossed));

I know that there are better ways to figure out if a needle crosses the line, but this works well enough. Plus, I wanted to make a really neat visualization. Speaking of which (note: red needles are crossing the line, blue are not):



Simulation speed

slow (1.0 Hz)
normal (0.5 Hz)
fast (0.1 Hz)
very fast (0.01 Hz)
as fast as possible
even faster
light speed
ludicrous speed

comments powered by Disqus