Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在单位圆上使用蒙特卡罗模拟估计'pi'时,'norm'函数的误差 ##在单位正方形上模拟'N'均匀分布的点 N_R_Simulation_Montecarlo_Pi - Fatal编程技术网

在单位圆上使用蒙特卡罗模拟估计'pi'时,'norm'函数的误差 ##在单位正方形上模拟'N'均匀分布的点 N

在单位圆上使用蒙特卡罗模拟估计'pi'时,'norm'函数的误差 ##在单位正方形上模拟'N'均匀分布的点 N,r,simulation,montecarlo,pi,R,Simulation,Montecarlo,Pi,norm会给出错误,因为它需要一个矩阵。然而,x[i,]不是一个矩阵,而是一个向量。换句话说,当您从矩阵中提取单个行/列时,其维度将被删除。您可以使用x[i,drop=FALSE]来维护矩阵类 第二个问题是,您需要L2规范。因此,将type=“2”设置为内部标准。总之,使用 ## simulate `N` uniformly distributed points on unit square N <- 1000 x <- matrix(runif(2 * N), ncol = 2)

norm
会给出错误,因为它需要一个矩阵。然而,
x[i,]
不是一个矩阵,而是一个向量。换句话说,当您从矩阵中提取单个行/列时,其维度将被删除。您可以使用
x[i,drop=FALSE]
来维护矩阵类

第二个问题是,您需要L2规范。因此,将
type=“2”
设置为内部标准。总之,使用

## 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
事实上,它们的效率更高。它们还支持在下面的矢量化方法中使用
行和


矢量化

我们可以通过以下方式避免循环:

sqrt(c(crossprod(x[i,])))
sqrt(sum(x[i,] ^ 2))
n
sqrt(c(crossprod(x[i,])))
sqrt(sum(x[i,] ^ 2))
n <- mean(sqrt(rowSums(x ^ 2)) < 1)  ## or simply `mean(rowSums(x ^ 2) < 1)`