我正在做一个关于圆周率的蒙特卡罗近似的练习.

由于某种原因,当所有的变量都被定义时,曲线图是空的,你能帮我吗?

以下是代码:

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))

Empty plot

I tried : check if the variables pi_4_estimate and pi_estimate are correctly calculated. Modifying the plot parameters
restarting RStudio and running the code again.

推荐答案

pi_estimate是接近圆周率的长度为-1的数值向量.当您try 将其绘制为一条线时,不会显示任何内容,因为一条线需要至少有两个点才能连接.

大概您想要展示的是,随着点数的增加,曲线下的点的比例如何逐渐接近pi/4.为此,您可以绘制under_curve的累积和除以沿under_curve的序列

set.seed(1) 

M <- 1e4 

sum_squares <- runif(M)^2 + runif(M)^2
under_curve <- sum_squares < 1 

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)

enter image description here

R相关问答推荐

使用sensemakr和fixest feols模型(R)

为什么当我try 在收件箱中使用合并功能时会出现回收错误?

如何删除R中除某些特定名称外的所有字符串?

R:连接值,而不是变量?

将向量组合到一个数据集中,并相应地命名行

二维样条,严格以一个参数递增

将数字转换为分钟和秒

多个模拟序列间的一种预测回归关系

按列中显示的配对组估算NA值

R+reprex:在呈现R标记文件时创建可重现的示例

使用未知字符数(不受限制的最大长度)的Lookback有什么好的替代方案?

在R中的数据框上使用Apply()函数时,如何保留非数字列?

有没有办法通过str_Detect()或其他字符串匹配函数来连接两个长度不等的数据帧?

我需要使用ggplot2制作堆叠条形图

R预测包如何处理ARIMA(Auto.arima函数)中的缺失值

如何获取R chromote中的当前URL?

隐藏基于 case 总数的值

R没有按顺序显示我的有序系数?

将仪表板中的值框大小更改为Quarto

将`magick`对象转换为原始向量