Monte Carlo Simulations in R for Beginners
Summary
Monte Carlo Simulations provide a powerful technique for analyzing uncertain scenarios using repeated random sampling. This tutorial will walk you through the process of conducting a simple Monte Carlo Simulation in R, even if you're new to the concept. We'll cover everything from installing R to visualizing your simulation results.
Step 1: Install R and RStudio
- Download and install R from R's official website.
- Install RStudio, an IDE for R, from RStudio's official website.
Step 2: Write Your First R Script
- Open RStudio.
- Start a new script (File > New File > R Script).
- Write or paste the following code:
# Monte Carlo Simulation Example
simulate <- function() {
x <- runif(1)
y <- runif(1)
if (x^2 + y^2 <= 1) return(1)
return(0)
}
simulations <- 10000
hits <- 0
for(i in 1:simulations) {
hits <- hits + simulate()
}
pi_estimate <- (hits / simulations) * 4
print(pi_estimate)
This code simulates throwing darts at a square board and calculates an estimate of π.
Step 3: Run the Simulation
- Save your script (File > Save).
- Click 'Run' to execute the script.
Step 4: Interpret the Results
- Your result is an approximation of π, based on 10,000 simulations.
- You can increase the number of simulations to get a more accurate result.
Step 5: Visualize the Simulation (Optional)
- Add this code to create a plot:
plot(NA, xlim=c(-1,1), ylim=c(-1,1), asp=1, xlab="", ylab="")
for(i in 1:simulations) {
x <- runif(1, -1, 1)
y <- runif(1, -1, 1)
if(x^2 + y^2 <= 1) {
points(x, y, col="blue")
} else {
points(x, y, col="red")
}
}
- Run the script again to see the plot.
Conclusion
You've successfully conducted a Monte Carlo Simulation in R, demonstrating the approximation of π. By understanding this basic example, you can begin to explore more complex simulations relevant to your field of study or work.
If you have any questions or want to know more, please leave a comment in the comment section below!