Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # estimating Pi using simple Monte Carlo Metod
- # method: http://en.wikipedia.org/wiki/Monte_Carlo_method
- # blog: http://reakt.com
- library(plotrix)
- library(grid)
- # distance between points 'x' and 'y'
- distance <- function(x,y) {
- n <- length(x)
- if (n!=length(y)) stop("Different X and Y dimensions.")
- sqrt(sum(sapply(1:n, function(i) (x[i]-y[i])^2)))
- }
- # number of points drawn
- n <- 1000
- x <- runif(n,0,1)
- y <- runif(n,0,1)
- # plot points and circle
- plot(x,y,type="p",pch=16,asp=1)
- draw.circle( 0, 0, 1 )
- # distance between points and the center of the circle
- d <- sapply(1:n, function(i) distance(c(0,0),c(x[i],y[i])))
- # proportion of points inside the circle * 4 -> pi
- pi.mc <- length(which(d<=1))/n*4
- points(x[which(d<=1)],y[which(d<=1)],col="Red",pch=16)
- # Monte Carlo Pi estimation:
- pi.mc
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement