简体   繁体   中英

Monte Carlo pi method

I try to calculate Monte Carlo pi function in R. I have some problems in the code. For now I write this code:

ploscinaKvadrata  <- 0
ploscinaKroga <- 0
n = 1000
for (i in i:n) {
  x <- runif(1000, min= -1, max= 1)
  y <- runif(1000, min= -1, max= 1)
  if ((x^2 + y^2) <= 1) {
    ploscinaKroga  <- ploscinaKroga + 1
  } else {
    ploscinaKvadrata <- ploscinaKvadrata + 1
  }
    izracunPi = 4* ploscinaKroga/ploscinaKvadrata
}

izracunPi

This is not working, but I don't know how to fix it.

I would also like to write a code to plot this (with circle inside square and with dots).

Here is a vectorized version (and there was also something wrong with your math)

N <- 1000000
R <- 1
x <- runif(N, min= -R, max= R)
y <- runif(N, min= -R, max= R)
is.inside <- (x^2 + y^2) <= R^2
pi.estimate <- 4 * sum(is.inside) / N
pi.estimate
# [1] 3.141472

As far as plotting the points, you can do something like this:

plot.new()
plot.window(xlim = 1.1 * R * c(-1, 1), ylim = 1.1 * R * c(-1, 1))
points(x[ is.inside], y[ is.inside], pch = '.', col = "blue")
points(x[!is.inside], y[!is.inside], pch = '.', col = "red")

but I'd recommend you use a smaller N value, maybe 10000.

This is a fun game -- and there are a number of versions of it floating around the web. Here's one I hacked from the named source (tho' his code was somewhat naive).

from http://giventhedata.blogspot.com/2012/09/estimating-pi-with-r-via-mcs-dart-very.html

est.pi <- function(n){

# drawing in  [0,1] x [0,1] covers one quarter of square and circle
# draw random numbers for the coordinates of the "dart-hits"
a <- runif(n,0,1)
b <- runif(n,0,1)
# use the pythagorean theorem
c <- sqrt((a^2) + (b^2) )

inside <- sum(c<1)
#outside <- n-inside

pi.est <- inside/n*4

 return(pi.est)
}

Typo 'nside' to 'inside'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM