Search code examples
rmontecarlopisample-size

R: calculating approximation error of pi approximation with monte carlo


I'm new to computer simulations and R programming as a new module I had to study in college I had some issues understanding the problem asking in an exercise

The code I'm trying with :

runs <- 100000
#runif samples from a uniform distribution
xs <- runif(runs,min=-0.5,max=0.5)
ys <- runif(runs,min=-0.5,max=0.5)
in.circle <- xs^2 + ys^2 <= 0.5^2
mc.pi <- (sum(in.circle)/runs)*4
# absdif <- abs(mc.pi - 3.14159265)
# print(absdif)
plot(xs,ys,pch=".",col=ifelse(in.circle,"blue","red"),xlab='',ylab='',asp=1, main=paste("MC Approximation of Pi =",mc.pi))

Is the variable "runs" considered as the sample size in the exercise ? Thanks in advance for your help


Solution

  • Yes, the runs variable configures how many samples are drawn, so it is the way you configure the sample size in this code. If you look at the ?runif help page, the first argument is the number of samples to draw, so your code runif(runs, ...) draws runs sample points from a uniform distribution.