# L-11 MCS 507 Fri 15 Sep 2023 : estimatepimt.jl # Multithreaded version of a Monte Carlo simulation. # At the command prompt type for example: # time JULIA_NUM_THREADS=8 julia estimatepimt.jl # to run the code with 8 threads. using Base.Threads import Statistics myrand(x::Int64) = (1103515245x + 12345) % 2^31 """ function estimatepi(n) Runs a simple Monte Carlo method to estimate pi with n samples. """ function estimatepi(n) r = threadid() count = 0 for i=1:n r = myrand(r) x = r/2^31 r = myrand(r) y = r/2^31 count += (x^2 + y^2) <= 1 end return 4*count/n end nt = nthreads() println("The number of threads : $nt") estimates = zeros(nt) timestart = time() @threads for i=1:nt estimates[i] = estimatepi(10_000_000_000/nt) end estpi = Statistics.mean(estimates) elapsed = time() - timestart println("The estimate for Pi : $estpi") println("The elapsed time : $elapsed seconds")