Buffon's Needle Problem

BuffonsNeedle[r_,{x_,y_},n_]:=Module[
{
data=Table[{{x Random[Real],y Random[Real]},π Random[Real]},{n}],
lines,hits,misses
},
Graphics[lines=(Function[s,First[#]+s  r/2 Through[{Cos,Sin}[Last[#]]]]/@{1,-1})&/@data;
{
Line[{{#,0},{#,y}}]&/@Range[0,Ceiling[x]],
PointSize[.01],
{misses,hits}=Map[Last,Split[Sort[Transpose[{Abs[Subtract@@(Floor/@First/@#)&/@lines],lines}]],(First[#1]==First[#2]&)],{2}];
Transpose[{
{RGBColor[1,.47,0],RGBColor[.67,.75,.15]},
{Line/@#}&/@{hits,misses}
}]
}, PlotLabel-> Column[{
Style[
Row[{"hit ratio: ",ToString[TraditionalForm["hits"/"N"]]," = ",With[{a=Length[hits],b=n},HoldForm[a/b]]," ≈ ",ToString[Round[100Length[hits]/n]],"%"}],"Label"],
Style[
Row[{"π"," ≈ ",ToString[TraditionalForm[("2 × L × N")/"hits"]]," = ",With[{a=Length[hits],b=n, c=r},HoldForm[(2c b)/a]]," ≈ ",ToString[N[2n r/Length[hits]]]}],
"Label"]}],PlotRange->{{-1/2,x+1/2},{-1/2,y+1/2}},ImageSize->{400,300}]
];

Manipulate[SeedRandom[sr];BuffonsNeedle[length,{10,6},needles],{{needles,200,"number of needles (N)"},20,1000,1,Appearance-> "Labeled"},{{length,.6,"needle length (L)"},.25,1,Appearance-> "Labeled"},{{sr,12,"random seed"},1,100,1},SaveDefinitions->True]

CAPTION

Toss a box of N needles onto a floor with parallel lines. Count the number of hits—that is, the number of times that a needle crosses a line. This turns out to be a method for estimating π.

THIS NOTEBOOK IS THE SOURCE CODE FROM

"Buffon's Needle Problem" from the Wolfram Demonstrations Project
 http://demonstrations.wolfram.com/BuffonsNeedleProblem/

Contributed by: Ed Pegg Jr and Eric W. Weisstein

A full-function Wolfram Mathematica system (Version 6 or higher) is required to edit this notebook.
GET WOLFRAM MATHEMATICA »

© Wolfram Demonstrations Project & Contributors   |   Terms of Use   |   Make a new version of this Demonstration »