Coding challenge

In 1777, Georges-Louis Leclerc, Comte de Buffon, posed a famous question: if you drop a needle of length $L$ on floorboards of width $D$ (where $L \le D$), the probability that the needle crosses a seam between boards is: $$P = \frac{2L}{\pi D}$$ Let $L = 1$ and $D = 1$. The needle's center distance $y$ to the nearest line is uniform between $0$ and $0.5$, and its angle $\theta$ with the lines is uniform between $0$ and $\pi/2$. The needle crosses if $y \le \frac{1}{2}\sin\theta$.

Simulate $10{,}000$ drops using math.random(). From the count of crossings, estimate $\pi = \frac{2 \times \text{total}}{\text{crossings}}$. How close to $3.1415...$ do you get?

Type your code here:


Lua reference

See your results here: