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
Mar 27, 2020
pi@raspberrypi:~ $ julia -p auto -L buffon.jl
_
_ _ _(_)_ | Documentation: https://docs.julialang.org
(_) | (_) (_) |
_ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help.
| | | | | | |/ _` | |
| | |_| | | | (_| | | Version 1.6.0-DEV.718 (2020-08-25)
_/ |\__'_|_|_|\__'_| | Commit 3d04d15c31* (0 days old master)
|__/ |
julia> versioninfo()
Julia Version 1.6.0-DEV.718
Commit 3d04d15c31* (2020-08-25 10:29 UTC)
Platform Info:
OS: Linux (arm-linux-gnueabihf)
CPU: ARMv7 Processor rev 3 (v7l)
WORD_SIZE: 32
LIBM: libopenlibm
LLVM: libLLVM-9.0.1 (ORCJIT, cortex-a72)
julia> main()
3.1416373061286977
124.725025 seconds (402.14 k allocations: 14.191 MiB, 0.02% gc time)
3.141535930876609
35.777320 seconds (77.27 k allocations: 3.251 MiB, 0.06% gc time)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment