Ever since learning about Buffon’s needle, I have always wanted to write a small simulation as a programming exercise for myself, and to just admire the fact that it works.

For those unaware, Buffon’s needle (or one variant of it) was a geometric probability problem that had the following setup. Given an infinite table with equally spaced vertical lines, and a needle (smaller than the spacing between lines) twirled and tossed randomly onto the table, what is the probability that it crosses one of the vertical lines?

The answer can be derived with some calculus, but I won’t go into details here. There are plenty of other sources for that. The main gist though is that the solution contains π in it! This allows us to estimate the value of π by experimentally tossing many needles and approximating the probability of crossing a line.

In the end, I wrote a small simulation with JavaScript that is running on GitHub pages. Below are relevant links.