我正在做圆周率的蒙特卡罗近似练习。
由于某种原因,当定义所有变量时,绘图是空的,你能帮我吗?
这是代码:
set.seed(1)
M = 10^4
U = matrix(runif(2*M), ncol = 2)
sum_squares = U[,1]^2 + U[,2]^2
under_curve = sum_squares < 1
points_under_curve = U[under_curve,]
points_over_curve = U[!under_curve,]
pi_4_estimate = sum(under_curve)/M
cat("Estimation of π/4 = ", pi_4_estimate)
pi_estimate = pi_4_estimate * 4
cat("Estimation of π = ", pi_estimate)
plot(pi_estimate, type = "l", xlab = "Number of Simulations", ylab = "Estimation of Pi", main = "Convergence of Monte Carlo Estimator of Pi", xlim = c(0,M))
我尝试过:
检查变量 pi_4_estimate 和 pi_estimate 是否计算正确。
修改绘图参数
重新启动 RStudio 并再次运行代码。
pi_estimate
是一个接近 pi 的长度为 1 的数值向量。当您尝试将其绘制为一条线时,不会出现任何内容,因为一条线需要至少有两个点才能连接。
大概您想要展示的是,随着点数的增加,曲线下方的点的比例如何逐渐接近 pi/4。为此,你可以这样做
estimator <- 4 * cumsum(under_curve) / seq_along(under_curve)
plot(estimator,
type = "l",
xlab = "Number of Simulations",
ylab = "Estimation of Pi",
main = "Convergence of Monte Carlo Estimator of Pi",
xlim = c(0, M))
abline(h = pi, lty = 2)