Hello,
Goal: Estimating PI by throwing darts in a square and checking if they hit the unit-circle.
I have 2 questions:
- Why does the following code always underestimate the value of PI?
- Second piece of code: Why does wrapping the for-loop in a @sync eat up all the memory?
darts_cpu_multithreading.jl
function throw_dart()
x = rand() * 2 - 1
y = rand() * 2 - 1
return( (x*x + y*y) <= 1 )
end
function estimate_pi(N)
println("Running estimate PI with MULTI threading on CPU. nr of threads: ", Threads.nthreads())
hits_in_circle = 0
for _ = 1:N
Threads.@spawn begin
hits_in_circle = hits_in_circle + throw_dart()
end
end
pi_est = 4 * hits_in_circle / N
println("PI is ", pi_est)
end
const nr_of_throws = 2^24
estimate_pi(nr_of_throws)
I run the code like this:
julia.exe --threads=auto d:\projects\julia\estimate_pi\darts_cpu_multithreading.jl
But something like this comes out every time:
C:\Users\Erwin>julia.exe --threads=auto d:\projects\julia\estimate_pi\darts_cpu_multithreading.jl
Running estimate PI with MULTI threading on CPU. nr of threads: 8
PI is 2.893035650253296
C:\Users\Erwin>julia.exe --threads=auto d:\projects\julia\estimate_pi\darts_cpu_multithreading.jl
Running estimate PI with MULTI threading on CPU. nr of threads: 8
PI is 2.9227113723754883
etc. etc. Always too low.
Second question: 2) Second piece of code: Why does wrapping the for-loop in a @sync eat up all the memory?
Reason: I (naively) expected that the for-block maybe needed to finish, so I tried to sync it, but that didn’t work either.
This following code doesn’t work nicely: (Only added that @sync)
function throw_dart()
x = rand() * 2 - 1
y = rand() * 2 - 1
return( (x*x + y*y) <= 1 )
end
function estimate_pi(N)
println("Running estimate PI with MULTI threading on CPU. nr of threads: ", Threads.nthreads())
hits_in_circle = 0
@sync for _ = 1:N
Threads.@spawn begin
hits_in_circle = hits_in_circle + throw_dart()
end
end
pi_est = 4 * hits_in_circle / N
println("PI is ", pi_est)
end
const nr_of_throws = 2^24
estimate_pi(nr_of_throws)