Estimate pi with simulation

Imagine we have a circle with radius 1 is inscribed in a square with length 2. Then, we randomly generate points in the square. The probability of that point is in the circle is the area of the circle over the area of the square, which is \(\frac{area of circle}{area of square}\) = \(\frac{\pi * 1^2}{2^2}\) = \(\frac{\pi}{4}\)

# Create a simulation function
estimate.pi = function(n)
{
  distance <- c()
  successes = 0
  for (i in 1:n)
    {
    # Generate the x-y coordinates of simulation points where x and y are both between 1 and -1
    RandomDot <- runif(2, -1, 1) # runif(n, min = 0, max = 1)
    # Calculate the distance between the simulation and the origin
    RandomDot_Distance <- (RandomDot[1]^2 + RandomDot[2]^2)^0.5
    # If the distance is greater than 1, the point is not in the circle
    if (RandomDot_Distance <= 1)
      {
      successes = successes + 1    
      }
  }
  # The simulated value of pi would be 4 * the probability of the proportion of points in the circle
  return((successes/n) * 4)      
}
set.seed(1)
estimate.pi(10)
## [1] 3.6
estimate.pi(1000000)
## [1] 3.143856
estimate.pi(1000000000)
## [1] 3.141581