### Exercise 1 - Exploring the effect of larger samples

### This Monte Carlo simulation approximates pi using the circle in square method

# Set up the random number generator using a seed number
# This will give you a reproducible set of random numbers
# If you do not need to be able to reproduce the same set of random numbers
# then line 10 can be removed

set.seed(42)

# Set up a loop vector with the numbers of instances for each simulation

sim_size<-c(10,100,1000,10000,100000,1000000,10000000,100000000)

# Set up a null vector to same the estimations

sim_pi<-NULL

# Create loop based on loop vector sim_size

for (n in sim_size)
{

  # Generate n random values of x and y between -1 and +1
  # runif(n, min, max) generates a vector of n elements with values randomly
  # distributed between min and max

  x<-runif(n,-1,1)
  y<-runif(n,-1,1)

  # Run the simulation
  # The model in this case is the equation that defines the condition where x and y
  # fall within the circle defined by x^2 + y^2 <= 1

  inside<-x^2 + y^2 <= 1

  # Using inside, calculate the estimated value of pi using the mean of all inside values
  # We don't care what the x,y values are, only whether they are inside (TRUE)
  # or outside (FALSE). As the Booleans are represented by 1 and 0 we can take the
  # mean of the vector inside to calculate the proportion that are TRUE

  pi_estimate <- 4 * mean(inside)

  # Add current pi_estimate to sim_pi

  sim_pi<-c(sim_pi,pi_estimate)

}# End of main loop

# Plot sim_size against sim_pi as both dots and line in red

plot(sim_size, sim_pi, type="b", col = "red")

