rplotmontecarlopiis-empty

Why my Monte Carlo estimation of pi plot is empty?


I am doing an exercice on the Monte Carlo approximation of pi.

For some reason the plot is empty when all the variables are defined, could you help me ?

Here is the code :

set.seed(1) 

M = 10^4  

U = matrix(runif(2*M), ncol = 2) 

sum_squares = U[,1]^2 + U[,2]^2  
under_curve = sum_squares < 1 


points_under_curve = U[under_curve,] 
points_over_curve = U[!under_curve,] 

pi_4_estimate = sum(under_curve)/M
cat("Estimation of π/4 = ", pi_4_estimate)

pi_estimate = pi_4_estimate * 4
cat("Estimation of π = ", pi_estimate)


plot(pi_estimate, type = "l", xlab = "Number of Simulations", ylab = "Estimation of Pi", main = "Convergence of Monte Carlo Estimator of Pi", xlim = c(0,M))

Empty plot

I tried : check if the variables pi_4_estimate and pi_estimate are correctly calculated. Modifying the plot parameters
restarting RStudio and running the code again.


Solution

  • pi_estimate is a length-1 numeric vector close to pi. When you try to plot it as a line, nothing appears because a line needs to have at least two points to join.

    Presumably what you want to show is how the proportion of points that is under the curve progressively approaches pi/4 as the number of points increases. For that, you can plot the cumulative sum of under_curve divided by the sequence along under_curve

    set.seed(1) 
    
    M <- 1e4 
    
    sum_squares <- runif(M)^2 + runif(M)^2
    under_curve <- sum_squares < 1 
    
    estimator <- 4 * cumsum(under_curve) / seq_along(under_curve)
    
    plot(estimator,
         type = "l", 
         xlab = "Number of Simulations", 
         ylab = "Estimation of Pi", 
         main = "Convergence of Monte Carlo Estimator of Pi", 
         xlim = c(0, M))
    
    abline(h = pi, lty = 2)
    

    enter image description here