# approximation of PI using random numbers and large iterations
# the surface of a square of one by one = 1
# the program will generate random numbers between 0 and 1
# these are x and y as coordinates, plotting spots witin the 1 by 1 square
# a circle within that square has a (R)radius of 0.5
# all spots will land within the square, but not all spots will land within the circle
# the surface of the circle within the square is PI multiplied by R square,
# so effectively 0.25 pi
# iterations is the number of random spots
# counter counts the number of spots within the inner circle
# counter / iterations = 0.25 PI /1
# PI = 4 multiplied by (counter / iterations)
# single core
# clean all
rm(list=ls())
# to easily set the number of iterations
power10=5
iterations <- 10^power10
start <- proc.time()
counter <- 0
for (i in 1:iterations) {
x <- runif(1)
y <- runif(1)
xd <- x-0.5
yd <- y-0.5
xsqr <- xd*xd
ysqr <-yd*yd
incircle <- xsqr+ysqr
if (incircle<0.25) counter <- counter +1
}
end <- proc.time()
time_singlecore <- (end - start)[3]
print("The execution time was : ")
time_singlecore
PiApprox <- (counter/iterations)*4
print("Approximation of PI : " )
PiApprox
#parallel version
# clean all
rm(list=ls())
library(doParallel)
cl <- makeCluster(4)
registerDoParallel(cl)
# to easily set the number of iterations
power10=5
iterations <- 10^power10
start <- proc.time()
counter_p <- 0
total_p <- foreach (i = 1:iterations, .combine= "+" ) %dopar% {
x <- runif(1)
y <- runif(1)
xd <- x-0.5
yd <- y-0.5
xsqr <- xd*xd
ysqr <- yd*yd
incircle <- xsqr+ysqr
(incircle<0.25)
}
end <- proc.time()
time_parallel <- (end - start)[3]
print("The execution time in paralel mode was : ")
print(time_parallel)
PiApprox_p <- (total_p/iterations)*4
print("Approximation of PI : ")
PiApprox_p
stopCluster(cl)`
I have played with example code and doParallel and get the idea high level. Yet I am probably making a large mistake as my own code slows down 100x when I use doparallel. I would expect a speed up certainly when numbers increase.(overhead of map and reduce effect should then be less) No doubt a silly beginners mistake but I can not find it myself. Thanks for the help