简体   繁体   中英

Monte Carlo integration in R

I need to apply Monte Carlo integration to a function using R. I am able to plot the equation, but am unaware on how to plot random points over it.

Would appreciate any insight on how to do that.

The function I'm using to plot, is the basic plot() function with x as the desired range and y as the equation.

Thank you.

The nicest way to plot a curve is to use the curve function:

f = function(x) x^2 + 1   
curve(f(x), -2,2, ylim=c(0, 5))

You can then add points to the plot via the points function:

points(runif(100, -2, 2), runif(100, 0, 6))

and calculate the Monte-Carlo estimate using a comparison:

N = 100000
sum(f(runif(N, -2, 2)) > runif(N, 0, 6))/N * (4*6)

在此处输入图片说明

You can generate random points with

xx <- runif(100,min=0,max=1)
yy <- runif(100,min=0,max=1)

and add them to an existing plot with

points(xx,yy)

See ?points for the help page.

Here's my version of a solution given that I understand you correctly.

Basic code:

    x<-seq(-4,4,0.1)
    y<-2*x^2-3*x
    plot(x,y)
    points(x, rnorm(length(x), 20, 10), col="red")

This adds random points coloured in red to your existing function.

视觉效果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM