Created
April 9, 2015 15:55
-
-
Save tanmaykm/fd203bd51540ad172cf5 to your computer and use it in GitHub Desktop.
Monte Carlo Pi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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