Skip to content

Instantly share code, notes, and snippets.

@andrie
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrie/ceefce30c1b06dba2b32 to your computer and use it in GitHub Desktop.
Save andrie/ceefce30c1b06dba2b32 to your computer and use it in GitHub Desktop.
library(foreach)
library(doParallel)
# Estimate value of pi using simulation
mcPi <- function(n=1e6) 4 * sum( runif(n)^2 + runif(n)^2 < 1) / n
# Set up cluster
cl <- makeCluster(4)
registerDoParallel(cl)
# Run simulation
est <- foreach(icount(128), .combine=c) %dopar% mcPi()
mean(est)
# Plot results
plot(density(est), main=expression(paste("Simulated value of ", pi)))
abline(v=mean(est), col="red", lwd="3")
abline(v=pi, col="black", lwd="3")
text(pi, 0, label=expression(pi), pos=2, cex=2)
text(mean(est), 50, label="Simulated value", pos=if(mean(est) < pi) 3 else 1,
cex=1, col="red", srt=90, adj=c(20, 20))
# Stop cluster
stopCluster(cl)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment