You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

蒙特卡洛法估算π的R语言绘图为空,请求技术支持

问题排查与修正

你的代码里绘图为空的核心原因是:pi_estimate是单一数值(最终的π近似结果),而type="l"要求输入连续序列来绘制折线,单个数据点无法生成折线,因此绘图区域显示为空。

要绘制蒙特卡洛估计π的收敛曲线,你需要计算每一步模拟的累计估计值,而非只保留最终结果。以下是修正后的代码:

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 

# 计算从第1到第M次模拟的累计π估计值
cumulative_pi_estimate = 4 * cumsum(under_curve) / (1:M)

# 输出最终估计结果
pi_4_estimate = sum(under_curve)/M
cat("Estimation of π/4 = ", pi_4_estimate, "\n")
pi_estimate = pi_4_estimate * 4
cat("Estimation of π = ", pi_estimate, "\n")

# 绘制收敛曲线
plot(cumulative_pi_estimate, type = "l", 
     xlab = "Number of Simulations", 
     ylab = "Estimation of Pi", 
     main = "Convergence of Monte Carlo Estimator of Pi",
     ylim = c(3, 3.2)) # 限定y轴范围,更清晰展示收敛趋势
# 添加真实π值的参考虚线
abline(h = pi, col = "red", lty = 2)
legend("bottomright", legend = c("Monte Carlo Estimate", "True π"),
       col = c("black", "red"), lty = c(1, 2))

关键修正说明:

  • 用cumsum(under_curve)计算从第1个到第M个模拟中,累计落在单位圆内的点数
  • 除以1:M(每一步的模拟次数)得到累计的π/4估计,再乘4得到每一步的π估计值
  • 此时cumulative_pi_estimate是长度为M的序列,满足type="l"绘制折线的要求
  • 添加真实π值的参考线,能更直观观察收敛效果

如果需要同时展示蒙特卡洛的散点(区分单位圆内/外的点),可以在绘制收敛曲线前添加以下代码:

# 绘制蒙特卡洛散点图
plot(U[,1], U[,2], pch = 16, cex = 0.5,
     xlab = "X", ylab = "Y", main = "Monte Carlo Points")
# 绘制单位圆边界
curve(sqrt(1 - x^2), 0, 1, add = TRUE, col = "blue")
curve(-sqrt(1 - x^2), 0, 1, add = TRUE, col = "blue")
# 标记圆内/外点
points(points_under_curve[,1], points_under_curve[,2], col = "green", pch = 16, cex = 0.5)
points(points_over_curve[,1], points_over_curve[,2], col = "red", pch = 16, cex = 0.5)

内容的提问来源于stack exchange,提问作者lou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 22:30:01