Skip to content

Instantly share code, notes, and snippets.

@CorySimon
Last active August 29, 2015 14:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CorySimon/c0d5ec519953c7bae757 to your computer and use it in GitHub Desktop.
Save CorySimon/c0d5ec519953c7bae757 to your computer and use it in GitHub Desktop.
Compute pi
function compute_pi(N::Int)
"""
Compute pi with a Monte Carlo simulation of N darts thrown in [-1,1]^2
Returns estimate of pi
"""
n_landed_in_circle = 0 # counts number of points that have radial coordinate < 1, i.e. in circle
for i = 1:N
x = rand() * 2 - 1 # uniformly distributed number on x-axis
y = rand() * 2 - 1 # uniformly distributed number on y-axis
r2 = x*x + y*y # radius squared, in radial coordinates
if r2 < 1.0
n_landed_in_circle += 1
end
end
return n_landed_in_circle / N * 4.0
end
@everywhere function compute_pi(N::Int)
"""
Compute pi with a Monte Carlo simulation of N darts thrown in [-1,1]^2
Returns estimate of pi
"""
n_landed_in_circle = 0 # counts number of points that have radial coordinate < 1, i.e. in circle
for i = 1:N
x = rand() * 2 - 1 # uniformly distributed number on x-axis
y = rand() * 2 - 1 # uniformly distributed number on y-axis
r2 = x*x + y*y # radius squared, in radial coordinates
if r2 < 1.0
n_landed_in_circle += 1
end
end
return n_landed_in_circle / N * 4.0
end
function parallel_pi_computation(N::Int; ncores::Int=8)
"""
Compute pi in parallel, over ncores cores, with a Monte Carlo simulation throwing N total darts
"""
# compute sum of pi's estimated among all cores in parallel
sum_of_pis = @parallel (+) for i=1:ncores
compute_pi(int(N/8))
end
return sum_of_pis / ncores # average value
end
function parallel_estimate_of_N()
"""
Computes estimate of pi for an array of N
"""
N = logspace(4, 8)
return pmap(compute_pi, int(N))
end
N = logspace(0,7)
estimates = pmap(compute_pi, N)
job = @spawn compute_pi(1000000000)
fetch(job)
function serial_estimate_of_N()
"""
Computes estimate of pi for an array of N
"""
N = logspace(4,8)
pi_estimate = zeros(length(N))
for i = 1:length(N)
pi_estimate[i] = compute_pi(int(N[i]))
end
return pi_estimate
end
julia -p 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment