Simulating Buffon's needle problem

Buffon's needle problem is a classic problem on geometric probability. mathworld describes the problem quite well, and gives the following formula for the probability that the needle touches a line:

\begin{equation*} \displaystyle \mathbb{P}(x)=\begin{cases} \dfrac{2}{\pi}\, x& x\le 1\\ & \\ \dfrac{2}{\pi}\, \left(x-\sqrt{x^2-1}+\sec^{-1}{x}\right)& x>1 \end{cases} \end{equation*}

How can we convince ourselves that the formula has been derived correctly? How to simulate geometric shapes?

The answer is to use the parametric representation of the points. If the needle of length \(l\) is dropped, then it makes an angle \(\theta\) with the horizontal. For simulating, take one end of the needle as a reference, and it must be randomly and uniformly distributed in \([0,d)\). Call the random number as \(h\). The other end of the needle will then be at a distance \(h+l\cdot sin(\theta)\).

Now, for the condition that the needle touches the line, the other end must be either higher than \(d\) or less than zero. Hence, we can simulate the experiment by picking \(h\) in \(U(0,d)\) and \(\theta \in U(0,2\, \theta)\).

Following is the code in J:

1
2
3
4
5
6
7
8
load 'trig'
'l d'=:4 1
    sim =: 3 : 0
h=:d*?1000000#0
th=:2p1*?1000000#0
(+/%#)((h+l*sin th)>d)+.((h+l*sin th)<0)
)
    sim 0

It gives an answer about \(0.919978\), and changing \(l\) and \(d\) to

'l d'=:1 4

gives about \(0.15907\), which are close to actual answers \(0.920000066713994\) and \(0.159154943091895\), respectively.