Question

Trying to find integral (o to pi/2) of x^2 cosx using montecarlo method. This is my first time so need some direction. To generate random number should I transform the limit of the integral to (0,1) or can I generate random numbers with the given limit (0 to pi/2) ?

something like this ?

transform the integral from (o to pi/2) to (0to 1) which tranforms the function to 1/x^2 sinx generate random number rnorm(10000,0,1)

or Is there a way to generate random number like this rnorm(10000,0,1)*pi/2 with out having to transform the limit of the integral

Was it helpful?

Solution

You can generate random numbers uniformly in any interval you want, for example, runif(1000,0,pi/2) will generate a sample of size 1000 uniformly distributed on [0,π/2]. You definitely don't want to use rnorm here -- rnorm generates normally distributed data, not uniformly distributed data.

You could do your monte carlo simulation like this:

> f<-function(x) x^2 * cos(x)
> mean(f(runif(100000,0,pi/2)))*(pi/2)
[1] 0.4672985

Or, you can let R do the integration using integrate:

> integrate(f,0,pi/2)
0.4674011 with absolute error < 5.2e-15

OTHER TIPS

My first shoot:

mc.integral = function(FUN, n.iter = 1000, interval){

  # take a sample using 'runif'
  x = runif(n.iter, interval[1], interval[2])

  # apply the user-defined function
  y = FUN(x)

  # calculate
  mean(y)*(interval[2] - interval[1])
}

example

FUN = function(x){x^2 * cos(x)}
integ = mc.integral(FUN, interval = c(0, pi/2))
print(integ)

[1] 0.4693398
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top