R中的蒙特卡洛整合

isa*_*sal 0 r

我需要将蒙特卡洛积分应用于使用R的函数.我能够绘制方程,但我不知道如何在其上绘制随机点.

非常感谢有关如何做到这一点的任何见解.

我用来绘制的函数是基本的plot()函数,具有x所需的范围和y等式.

谢谢.

csg*_*pie 7

绘制曲线的最好方法是使用curve函数:

f = function(x) x^2 + 1   
curve(f(x), -2,2, ylim=c(0, 5))
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过以下points功能将点添加到绘图中:

points(runif(100, -2, 2), runif(100, 0, 6))
Run Code Online (Sandbox Code Playgroud)

并使用比较计算蒙特卡洛估计:

N = 100000
sum(f(runif(N, -2, 2)) > runif(N, 0, 6))/N * (4*6)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述