DAY 27
1

julia (27) -- 平行運算的實例:蒙地卡羅法計算圓周率

julia另一種常見的parallel computing模式是直接把for loop的運作平行化，像這樣:

``````@parallel for i=1:10000
rand()
end
``````

``````a=zeros(N)
@parallel for i=1:10000
a[i]=rand()
end
``````

``````function estimate_pi_vec()
# Vectorized way of calculating Pi
# This style is commonly seen in python or Matlab/Octave to avoid for loops

samplenum=100000000
mc_x=rand(samplenum,1)
mc_y=rand(samplenum,1)

R=0.5
mc_x=mc_x-R
mc_y=mc_y-R

mc_l2=mc_x.^2+mc_y.^2

r_sq=R^2

return sum(int(mc_l2.<r_sq))*4/samplenum
end
``````

``````function estimate_pi_loop(samplenum::Int64)
R=0.5
r_sq=R^2
incircle=0

incircle=@parallel (+) for i=1:samplenum

mc_x=rand()-R
mc_y=rand()-R
mc_l2=mc_x.^2+mc_y.^2

int(mc_l2<r_sq)
end

return incircle*4/samplenum
end
``````

``````\$ julia -p 3 monte_carlo_pi.jl
pi=3.1415854148
elapsed time: 21.955739032 seconds (15895304 bytes allocated)
``````

``````\$ julia monte_carlo_pi.jl
pi=3.14160138
elapsed time: 59.497772514 seconds (8692576 bytes allocated)
``````