Skip to content

Instantly share code, notes, and snippets.

@terasakisatoshi
Last active August 26, 2020 00:32
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 terasakisatoshi/11e76d62b642516ab2788e7bf569688d to your computer and use it in GitHub Desktop.
Save terasakisatoshi/11e76d62b642516ab2788e7bf569688d to your computer and use it in GitHub Desktop.
針をいっぱい投げる遊び throwing needle many times
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()
@terasakisatoshi
Copy link
Author

pi@rpi4:~/jlbench $ jldev -p auto -L buffon.jl
               _
   _       _ _(_)_     |  Documentation: https://docs.julialang.org
  (_)     | (_) (_)    |
   _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 1.4.0 (2020-03-21)
 _/ |\__'_|_|_|\__'_|  |
|__/                   |

julia> versioninfo()
Julia Version 1.4.0
Commit b8e9a9ecc6 (2020-03-21 16:36 UTC)
Platform Info:
  OS: Linux (arm-linux-gnueabihf)
  CPU: ARMv7 Processor rev 3 (v7l)
  WORD_SIZE: 32
  LIBM: libopenlibm
  LLVM: libLLVM-8.0.1 (ORCJIT, cortex-a72)
Environment:
  JULIA_NUM_THREADS = 4

julia> main()
3.1415344307516286
119.112676 seconds (474.79 k allocations: 14.237 MiB, 0.02% gc time)
3.141705696050348
 34.127721 seconds (752.97 k allocations: 27.785 MiB, 0.11% gc time)

@terasakisatoshi
Copy link
Author

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