Skip to content

Instantly share code, notes, and snippets.

@tanmaykm
Created April 9, 2015 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanmaykm/fd203bd51540ad172cf5 to your computer and use it in GitHub Desktop.
Save tanmaykm/fd203bd51540ad172cf5 to your computer and use it in GitHub Desktop.
Monte Carlo Pi
function buffon_one()
mp = rand()
phi = (rand() * pi) - pi / 2
xrechts = mp + cos(phi)/2
xlinks = mp - cos(phi)/2
xrechts >= 1 || xlinks <= 0
end
function buffon(m)
hit = 0
for l = 1:m
buffon_one() && (hit += 1)
end
miss = m - hit
piapprox = m / hit * 2
end
function buffon_par(m)
hit = @parallel (+) for l = 1:m
buffon_one() ? 1 : 0
end
miss = m - hit
piapprox = m / hit * 2
end
function dart_one()
xrand = rand()
yrand = rand()
r = sqrt(xrand^2 + yrand^2)
r <= 1
end
function dart(m)
hit = 0
for i in 1:m
dart_one() && (hit += 1)
end
piapprox = 4 * hit / m
end
function dart_par(m)
hit = @parallel (+) for i in 1:m
dart_one() ? 1 : 0
end
piapprox = 4 * hit / m
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment