3

我尝试在 R 中计算 Monte Carlo pi 函数。我在代码中遇到了一些问题。现在我写这段代码:

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

这不起作用,但我不知道如何解决它。

我还想编写一个代码来绘制这个(正方形内有圆圈和点)。

4

2 回答 2

9

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.

于 2013-03-03T13:54:23.870 回答
0

这是一款有趣的游戏——网上流传着许多版本。这是我从命名源中破解的一个(尽管他的代码有点天真)。

来自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)
}

错字'nside'到'inside'

于 2013-03-03T14:26:31.957 回答