Skip to content

Instantly share code, notes, and snippets.

@drewconway
Created March 14, 2011 21:28
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 drewconway/869923 to your computer and use it in GitHub Desktop.
Save drewconway/869923 to your computer and use it in GitHub Desktop.
A function for simulating the value of Pi using Monte Carlo.
# For this exercise we assume to draw random points inside the square on the [-1,1] unit,
# and thus the value of Pi = 4(# random pts insid cirlce / # random pts in square)
sim.pi <- function(iterations = 1000) {
# Generate two vectors for random points in unit circle
x.pos <- runif(iterations, min=-1, max=1)
y.pos <- runif(iterations, min=-1, max=1)
# Test if draws are inside the unit circle
draw.pos <- ifelse(x.pos^2 + y.pos^2 <= 1, TRUE, FALSE)
draws.in <- length(which(draw.pos == TRUE))
# Estimate Pi
return(4*(draws.in/iterations))
}
@chiraxjr
Copy link

pie=function(n){
count=0
for(i in 1:n){
if(runif(1,-1,1)^2+runif(1,-1,1)^2<=1)
count=count+1
}
return(4*(count/n))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment