在R中进行简单的蒙特卡洛积分时结果错误 [英] Wrong result when doing simple Monte Carlo integration in R

查看:163
本文介绍了在R中进行简单的蒙特卡洛积分时结果错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做关于数值积分的一部分演讲.尽管演讲本身将进入更好的数值积分形式(主要是重要性抽样和分层抽样),但在本节的一部分中,我会从均匀分布中提到蒙特卡洛积分抽样.

I'm giving part of a presentation on numerical integration. While the talk itself will go into better forms of numerical integration (mainly importance sampling and stratified sampling), I'm mentioning during part of my section Monte Carlo integration sampling from the uniform distribution.

我发现:

mean(sin(runif(1e8, 0, pi)))

给出的答案为0.636597,而不是预期的1.这个答案似乎与样本量的增加非常一致,我不确定为什么会有这么多错误.其他计算,例如:

is giving an answer of 0.636597, rather than 1 that is expected. This answer seems pretty consistent with increasing sample size, and I'm unsure why there's so much error. Other computations such as:

mean(sin(runif(1e6, 0, 2 * pi)))

给出0.0005398996,更接近0的预期答案.

give 0.0005398996, much closer to the expected answer of 0.

有人可以帮我看看原因

mean(sin(runif(1e8, 0, pi)))

给出的答案不正确吗?是用户错误,还是从均匀分布中采样时会发生这种错误?

is giving such an inaccurate answer? Is this user error, or is it to be expected when sampling from the uniform distribution?

推荐答案

我回来是为了使答案更完整,以防将来的读者需要了解其逻辑.请注意,如您的问题所述,真实值为2而不是1.

I came back to make my answer complete, in case future readers need to know the logic. Note, the true value is 2 not 1, as stated in your question.

因此,您只计算了样本的均值函数值,却忘记了乘以区间长度.

So, you just computed the mean function values at samples, but forgot to multiply interval length.

set.seed(0); pi * mean(sin(runif(1000, 0, pi)))
# [1] 2.001918

是您所需要的.

此结果的确定性视图是积分的均值定理,或积分的黎曼和近似.

A deterministic view of this result is mean value theorem for integral, or Riemann sum approximation of integral.

所以我们也可以做

pi * mean(sin(seq(0, pi, length = 1000)))
# [1] 1.997998


蒙特卡洛积分通过重要性抽样更加有用.阅读使用具有建议功能的重要性采样的蒙特卡洛积分作为一个很好的例子.


Monte Carlo integration is more useful via importance sampling. Read Monte Carlo integration using importance sampling given a proposal function for a good example.

这篇关于在R中进行简单的蒙特卡洛积分时结果错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆