Last active
August 26, 2020 00:32
-
-
Save terasakisatoshi/11e76d62b642516ab2788e7bf569688d to your computer and use it in GitHub Desktop.
針をいっぱい投げる遊び throwing needle many times
This file contains 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(n_trial) | |
hit_counter = zero(Bool) | |
for i in 1:n_trial | |
position = rand() | |
φ = (rand() * π) - π / 2 | |
x_right = position + cos(φ) / 2 | |
x_left = position - cos(φ) / 2 | |
is_hit = (x_right >= 1 || x_left <= 0) ? 1 : 0 | |
hit_counter += is_hit | |
end | |
approx_π = n_trial/hit_counter * 2 | |
end | |
using Distributed | |
function buffon_parallel(n_trial) | |
hit_counter = @distributed (+) for i in 1:n_trial | |
position = rand() | |
φ = (rand() * π) - π / 2 | |
x_right = position + cos(φ) / 2 | |
x_left = position - cos(φ) / 2 | |
(x_right >= 1 || x_left <= 0) ? 1 : 0 | |
end | |
approx_π = n_trial/hit_counter * 2 | |
end | |
function main() | |
@time println(buffon(convert(Int,1e9))) | |
@time println(buffon_parallel(convert(Int,1e9))) | |
end | |
#main() |
Author
terasakisatoshi
commented
Aug 26, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment