Monte Carlo Simulation Basics
Estimate pi and other quantities by repeated random sampling.
What Is Monte Carlo?
Monte Carlo simulation uses repeated random sampling to estimate quantities that are hard to compute analytically. Named after the casino in Monaco, it's used in finance, physics, statistics, and AI for integration, optimization, and inference.
# Core idea: approximate deterministic quantities
# using random sampling and the Law of Large Numbers
# Example: estimate probability that sum of two dice > 8
set.seed(42)
n <- 10000
die1 <- sample(1:6, n, replace = TRUE)
die2 <- sample(1:6, n, replace = TRUE)
total <- die1 + die2
# Monte Carlo estimate
mc_estimate <- mean(total > 8)
cat('MC estimate P(sum > 8):', mc_estimate, '\n')
# Exact probability
exact <- sum(outer(1:6, 1:6, '+') > 8) / 36
cat('Exact probability:', exact)Estimating Pi with Random Points
The classic Monte Carlo demo: randomly place points in a unit square. The fraction falling inside the unit circle estimates π/4. As n → ∞, the estimate converges to π.
set.seed(42)
n <- 100000
# Random points in [-1, 1] x [-1, 1] unit square
x <- runif(n, -1, 1)
y <- runif(n, -1, 1)
# Check if inside unit circle: x^2 + y^2 <= 1
inside <- (x^2 + y^2) <= 1
# Pi estimate: fraction inside * area of square
pi_estimate <- 4 * mean(inside)
cat('Pi estimate:', pi_estimate, '\n')
cat('True pi:', pi, '\n')
cat('Error:', abs(pi_estimate - pi))All lessons in this course
- set.seed() and Reproducibility
- Generating Random Distributions
- Monte Carlo Simulation Basics
- Bootstrap Resampling in R