r - 蒙特卡罗模拟 - 怎么了?
问题描述
我想使用函数的蒙特卡罗模拟计算曲线下的面积
到目前为止我的工作
# Define function f
f <- function(x) x^2 + 1
# I want to close my function in rectangle (-2, 2) - x axis and (1, 5) y -axis
n <- 10^6
# Randomize from x axis of rectangle
x_n <- runif(n, min = -2, max = 2)
# Randomize from y axis of rectangle
y_n <- runif(n, min = 1, max = 5)
# Calculate function values of randomized points
values <- f(x_n)
# Formula for are under the curve for monte carlo simulation is
# Area of rectangle * (Points below curve) / (Total number of points)
所以我的结果是:
> sum(y_n < values) / n * (4 * 4)
[1] 5.329888
这是不好的结果(正确的结果是 9.33333)。我做错了什么?当然,经过百万次采样后,算法应该更接近 9.3333
解决方案
这是一个显示您正在使用的内容的情节。我希望它能帮助您更好地理解我在评论中写的内容:
您似乎忽略了 y=1 下方的矩形。它的面积 (=4) 是缺失的数量。所以代码对于计算非偏移表达式 x^2 是正确的。更改为 y_n <- runif(n, min = 0, max = 5) 并重新运行计算
评论是答案的一半,即您没有模拟 y_n 的 0 和 1 之间的点。那些需要在蒙特卡洛模型中整合一个区域。另一个修改是将 [-2 < x <2]x[0<y<5] = 4*5 的正确总面积添加到正在考虑的总“面积”的计算中
f <- function(x) x^2 + 1
# I want to close my function in rectangle (-2, 2) - x axis and (1, 5) y -axis
n <- 10^6
# Randomize from x axis of rectangle
x_n <- runif(n, min = -2, max = 2)
# Randomize from y axis of rectangle
y_n <- runif(n, min = 0, max = 5)
# Calculate function values of randomized points
values <- f(x_n)
# Formula for are under the curve for monte carlo simulation is
# Area of rectangle * (Points below curve) / (Total number of points)
sum(y_n < values) / n * (5 * 4)
#[1] 9.3429 inaccurate to 1 or 2 parts in 933
显示第二种情况的 100 点图:
您可能考虑的另一个 mod 是使用 set.seed 使您的计算可重现。
推荐阅读
- sql-server - Kafka-Connect For MSSQL 无效值 java.sql.SQLException:找不到合适的驱动程序进行配置
- reactjs - 每次击键后反应输入失去焦点
- javascript - AJAX 打开和更改 xmlhttp.open
- gradle - 未从环境中获取 Gradle 包装器经过身份验证的下载凭据
- php - 路线 [purchase.store] 未定义
- typescript - 为什么解构数组项会导致联合类型?
- azure - 来自需要摘要式身份验证的逻辑应用的 HTTP 调用
- python - TypeError:“dict_values”对象不可下标
- c# - WPF / C#(无 MVVM)带倒计时时钟的计时器
- android - Gson fromJson 方法返回 null 解析 Stripe API 响应