Advertisement
mjaniec

Monte Carlo Pi esitmation

Aug 19th, 2012
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 0.84 KB | None | 0 0
  1.  
  2. # estimating Pi using simple Monte Carlo Metod
  3. # method: http://en.wikipedia.org/wiki/Monte_Carlo_method
  4. # blog: http://reakt.com
  5.  
  6. library(plotrix)
  7. library(grid)
  8.  
  9. # distance between points 'x' and 'y'
  10. distance <- function(x,y) {
  11.  
  12.   n <- length(x)
  13.  
  14.   if (n!=length(y)) stop("Different X and Y dimensions.")
  15.  
  16.   sqrt(sum(sapply(1:n, function(i) (x[i]-y[i])^2)))
  17.  
  18. }
  19.  
  20. # number of points drawn
  21. n <- 1000
  22.  
  23. x <- runif(n,0,1)
  24. y <- runif(n,0,1)
  25.  
  26. # plot points and circle
  27. plot(x,y,type="p",pch=16,asp=1)
  28. draw.circle( 0, 0, 1 )
  29.  
  30. # distance between points and the center of the circle
  31. d <- sapply(1:n, function(i) distance(c(0,0),c(x[i],y[i])))
  32.  
  33. # proportion of points inside the circle * 4 -> pi
  34. pi.mc <- length(which(d<=1))/n*4
  35.  
  36. points(x[which(d<=1)],y[which(d<=1)],col="Red",pch=16)
  37.  
  38. # Monte Carlo Pi estimation:
  39. pi.mc
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement