Created
March 14, 2011 21:28
-
-
Save drewconway/869923 to your computer and use it in GitHub Desktop.
A function for simulating the value of Pi using Monte Carlo.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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))
}