In []:
# If you don't have the package Graphics2D installed,
# Run the following command to get it
# Pkg.clone("git://github.com/sswatson/Graphics2D.jl.git")

In [1]:
using Graphics2D

In [2]:
using Gadfly

In [3]:
# n is the size of the box in which we're tossing needles
n = 10

Out[3]:
10

In [4]:
# generates a random triple of real numbers representing a needle
# of the form (xposition,yposition,angle)
function needle(n)
return (n*rand(), n*rand(), Ï€*rand())
end

function drawneedle(t)
return Line([t[1]-0.5*cos(t[3]) t[2]-0.5*sin(t[3]); t[1]+0.5*cos(t[3]) t[2]+0.5*sin(t[3])];
color =  hitline(t) ? green*0.5 : black )
end

# returns true or flase depending on whether the needle is hitting a line
function hitline(t)
return min(t[2]-floor(t[2]),1-(t[2]-floor(t[2]))) < sin(t[3])/2
end

Out[4]:
hitline (generic function with 1 method)

In [5]:
numtrials = 1000
showgraphics([[drawneedle(needle(n)) for _=1:numtrials],[Line([0 k; n k]) for k=0:n]])

Out[5]:
In [6]:
numtrials = 1_000_000
2/(sum([hitline(needle(n)) for _=1:numtrials])/numtrials)

Out[6]:
3.1428652245105773

In [7]:
Ï€

Out[7]:
Ï€ = 3.1415926535897...


In [8]:
# Chose the chord's midpoint from area measure on the disk
function randomchord1()
x,y = 2*rand()-1, 2*rand()-1
if x^2 + y^2 < 1
Î¸ = angle(x+im*y)
Ïˆ = acos(hypot(x,y))
return [(cos(Î¸-Ïˆ),sin(Î¸-Ïˆ)),(cos(Î¸+Ïˆ),sin(Î¸+Ïˆ))]
else
return randomchord1()
end
end

# Choose the chord's midpoint's polar coordinates
# from area measure on the rectangle [0,1] x [0,2Ï€]
function randomchord2()
r,Î¸ = rand(), 2Ï€*rand()
x,y = r*cos(Î¸), r*sin(Î¸)
if x^2 + y^2 < 1
Î¸ = angle(x+im*y)
Ïˆ = acos(hypot(x,y))
return [(cos(Î¸-Ïˆ),sin(Î¸-Ïˆ)),(cos(Î¸+Ïˆ),sin(Î¸+Ïˆ))]
else
return randomchord2()
end
end

# Choose the angles Î¸ and Ï† of the endpoints of the chord
# from area measure on [0,2Ï€] x [0,2Ï€]
function randomchord3()
Î¸,Ï† = 2Ï€*rand(), 2Ï€*rand()
return [(cos(Î¸),sin(Î¸)),(cos(Ï†),sin(Ï†))]
end

Out[8]:
randomchord3 (generic function with 1 method)

In [9]:
showgraphics([[Line(randomchord1()) for _=1:1000],[Circle((0,0),1)]])

Out[9]:
In [10]:
showgraphics([[Line(randomchord2()) for _=1:1000],[Circle((0,0),1)]])

Out[10]: