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