## simulate `N` uniformly distributed points on unit square
N <- 1000
x <- matrix(runif(2 * N), ncol = 2)
## count number of points inside unit circle
n <- 0; for(i in 1:N) {if (norm(x[i,]) < 1) {n <- n + 1} }
n <- n / N
## estimate of pi
4 * n
但我得到:
" norm(x [i,])中的错误:'a'必须是数字矩阵"
不确定怎么了。
norm
给您错误,因为它要求矩阵。但是,x[i, ]
不是矩阵,而是向量。换句话说,当您从矩阵中提取单行/列时,其尺寸会删除。您可以使用x[i, , drop = FALSE]
维护矩阵类。
第二个问题是,您想要 l2-norm 。因此,将type = "2"
设置在规范内。总共使用
norm(x[i, , drop = FALSE], type = "2") < 1
norm
不是唯一的解决方案。您也可以使用以下任何一个:
sqrt(c(crossprod(x[i,])))
sqrt(sum(x[i,] ^ 2))
实际上,它们更有效。他们还基于在下面的矢量化方法中使用rowSums
的想法。
矢量化
我们可以通过:
避免循环n <- mean(sqrt(rowSums(x ^ 2)) < 1) ## or simply `mean(rowSums(x ^ 2) < 1)`
sqrt(rowSums(x ^ 2))
给出了所有行的L2-Norm。与1(半径)进行比较后,我们得到了一个逻辑向量,TRUE
表示"圆内"。现在,您想要的值n
只是TRUE
的数量。您可以概括此逻辑向量,然后将N
分开,或者简单地对此向量。