x <- sample(1:6, 1, replace = TRUE) # sample() randomly selects 1 value from 1 to 6
cat("x =", x, "\n") # Print xx = 3
Let’s start with a die.
Roll a fair six-sided die and call it a success if you get a 4. If we repeat this experiment many times, we can calculate
\[ \frac{\text{number of successes}} {\text{number of repetitions}}. \]
Suppose we roll the die 10 times and get two 4s. Then
\[ \frac{2}{10}=0.20. \]
If we repeat the experiment 100 times, we might get 15 successes:
\[ \frac{15}{100}=0.15. \]
If we repeat it 10,000 times, the fraction will usually be much more stable.
This gives us a useful way to think about probability:
\[ P(\text{success}) \approx \frac{\text{number of successes}} {\text{number of repetitions}}. \]
More precisely, probability describes the long-run fraction of repetitions that are successes.
If we perform \(R\) repetitions and observe \(S\) successes, our numerical estimate is
\[ \hat p=\frac{S}{R}. \]
A computer can repeat a random experiment thousands or millions of times very quickly. Using repeated random experiments on a computer to study a probability or statistical prediction is called a Monte Carlo simulation.
To run a Monte Carlo simulation, we need an algorithm.
An algorithm is a set of instructions describing exactly what should be done. A recipe is a good analogy, but an algorithm should be detailed enough that someone else can follow it.
For our die problem:
Notice that there is no R in the algorithm. The same algorithm could be implemented in R, Python, Excel, or with an actual die.
Let’s see how R carries it out.
x <- sample(1:6, 1, replace = TRUE) # sample() randomly selects 1 value from 1 to 6
cat("x =", x, "\n") # Print xx = 3
Since success means getting a 4, we can have R keep track of whether this repetition is a success.
success <- 0 # Start success at 0
if (x == 4) { # If x equals 4
success <- success + 1 # Add 1 to success
} # } closes the if statement
cat("success =", success, "\n")success = 0
If we had rolled a 4, success would equal 1. Otherwise it equals 0.
Now let’s repeat the experiment 10 times and watch the simulation unfold.
R <- 10 # Set R to 10
success <- 0 # Set the success counter to 0
# Repeat the experiment R times
for (i in 1:R) {
x <- sample(1:6, 1, replace = TRUE) # Roll the die once
if (x == 4) {
success <- success + 1
}
cat("repetition =", i,
"x =", x,
"successes =", success, "\n")
} # } closes the for looprepetition = 1 x = 4 successes = 1
repetition = 2 x = 5 successes = 1
repetition = 3 x = 4 successes = 2
repetition = 4 x = 1 successes = 2
repetition = 5 x = 1 successes = 2
repetition = 6 x = 4 successes = 3
repetition = 7 x = 3 successes = 3
repetition = 8 x = 2 successes = 3
repetition = 9 x = 1 successes = 3
repetition = 10 x = 2 successes = 3
After the 10 repetitions, calculate
\[ \hat p=\frac{\text{number of successes}}{10}. \]
p.hat <- success / R
cat("p.hat =", p.hat, "\n")p.hat = 0.3
If you run the simulation again, you will probably get a different answer. That is exactly what we should expect: the simulation itself is random.
Once we understand what the simulation is doing, we can increase the number of repetitions.
R <- 10000
success <- 0
for (i in 1:R) {
x <- sample(1:6, 1, replace = TRUE)
if (x == 4) {
success <- success + 1
}
}
p.hat <- success / R
cat("p.hat =", p.hat, "\n")p.hat = 0.1677
This is the basic idea for Monte Carlo probability simulations:
\[ \boxed{\text{simulate one experiment}} \rightarrow \boxed{\text{decide if it is a success}} \rightarrow \boxed{\text{repeat}} \rightarrow \boxed{ \hat p= \frac{\text{successes}}{\text{repetitions}} } \]
The numerical simulation is only one part of what we will call a complete Monte Carlo algorithm.
A complete Monte Carlo algorithm has three parts:
\[ \boxed{\text{Theoretical Prediction}} \;\longrightarrow\; \boxed{\text{Numerical Simulation}} \;\longrightarrow\; \boxed{\text{Comparison}} \]
Together, these make a complete Monte Carlo algorithm.
This is the format you should use whenever you are asked to describe a Monte Carlo algorithm.
Let’s use the die problem again.
Question: What is the probability of rolling a 4 with a fair six-sided die?
State what theory predicts.
Here,
\[ p=P(\text{success}) =P(\text{roll a 4}) =\frac16. \]
The theoretical prediction will not always be this easy to calculate.
Probability theory may give us an exact answer, but finding it can require tools from a serious probability course. We don’t need to do that here.
If the exact probability is difficult to calculate, it is enough to write
\[ p=P(\text{success}) \]
and leave \(p\) unknown.
Compare
\[ \hat p \]
with
\[ p=\frac16. \]
With a sufficiently large \(R\), the two should be close.
That is a complete Monte Carlo algorithm.
So far, one repetition was one die roll.
Suppose instead we roll a fair six-sided die six times.
Question: What is the probability of getting exactly two 4s?
Here:
Probability theory can give us the exact probability, but we don’t need to calculate it.
\[ p=P(\text{success}). \]
Let’s first watch one repetition.
x <- sample(1:6, 6, replace = TRUE) # Roll the die 6 times
cat("x =", x, "\n")x = 5 1 1 1 2 3
This is six random outcomes, but it is still only one repetition.
n.fours <- sum(x == 4) # Count how many rolls are 4
cat("number of 4s =", n.fours, "\n")number of 4s = 0
success <- 0
if (n.fours == 2) { # Success means exactly two 4s
success <- 1
}
cat("success =", success, "\n")success = 0
Now repeat the complete six-roll experiment 10 times. To keep the output compact, rep means repetition, fours is the number of 4s, and total is the running number of successes.
R <- 10
success.total <- 0
for (i in 1:R) {
x <- sample(1:6, 6, replace = TRUE)
n.fours <- sum(x == 4)
success <- 0
if (n.fours == 2) {
success <- 1
}
success.total <- success.total + success
cat("rep =", i,
"x =", x,
"fours =", n.fours,
"success =", success,
"total =", success.total, "\n")
}rep = 1 x = 2 2 3 3 1 6 fours = 0 success = 0 total = 0
rep = 2 x = 4 2 2 1 6 3 fours = 1 success = 0 total = 0
rep = 3 x = 6 5 1 3 1 2 fours = 0 success = 0 total = 0
rep = 4 x = 2 2 6 2 4 4 fours = 2 success = 1 total = 1
rep = 5 x = 5 3 6 3 5 5 fours = 0 success = 0 total = 1
rep = 6 x = 2 5 1 1 5 4 fours = 1 success = 0 total = 1
rep = 7 x = 5 1 2 2 1 5 fours = 0 success = 0 total = 1
rep = 8 x = 5 1 6 4 6 6 fours = 1 success = 0 total = 1
rep = 9 x = 4 5 3 5 2 2 fours = 1 success = 0 total = 1
rep = 10 x = 6 4 4 4 5 1 fours = 3 success = 0 total = 1
p.hat <- success.total / R
cat("p.hat =", p.hat, "\n")p.hat = 0.1
We use \(R=10\) so that we can see what happens in every repetition. Once the simulation makes sense, use many more repetitions.
R <- 10000
success.total <- 0
for (i in 1:R) {
x <- sample(1:6, 6, replace = TRUE)
n.fours <- sum(x == 4)
if (n.fours == 2) {
success.total <- success.total + 1
}
}
p.hat <- success.total / R
cat("p.hat =", p.hat, "\n")p.hat = 0.196
Notice that the definition of success comes from the question.
n.fours == 2 # Exactly two 4s
n.fours >= 2 # At least two 4sIf the question changes from exactly two to at least two, the definition of success changes. The basic Monte Carlo structure does not.
Our theoretical prediction is
\[ p=P(\text{exactly two 4s in six rolls}). \]
Our simulation gives \(\hat p\).
If we know \(p\), compare \(p\) and \(\hat p\). If we do not calculate \(p\), then \(\hat p\) gives us a numerical approximation.
1. Theoretical Prediction
\[ p=P(\text{exactly two 4s in six rolls}). \]
2. Numerical Simulation
3. Comparison
Compare \(\hat p\) with \(p\). If \(p\) is not calculated analytically, use \(\hat p\) as its numerical approximation.
The important new idea is
\[ \boxed{\text{one repetition can contain many random outcomes}}. \]
So far, every outcome we generated was equally likely.
Suppose a prize wheel has three outcomes:
We spin the wheel three times.
Question: What is the probability of getting all three colors?
\[ p=P(\text{success}), \]
where success means getting red, blue, and green in the three spins.
Set up the wheel.
colors <- c("red", "blue", "green") # Possible outcomes
probs <- c(.20, .30, .50) # Their probabilitiesSpin once.
x <- sample(colors, 1, replace = TRUE,
prob = probs) # Sample using unequal probabilities
cat("x =", x, "\n")x = red
The important new part is
prob = probsIt tells R that the three outcomes are not equally likely. Without it, R would simulate the wrong prize wheel.
Now simulate one complete repetition.
x <- sample(colors, 3, replace = TRUE,
prob = probs)
cat("x =", x, "\n")x = red red green
success <- 0
if (length(unique(x)) == 3) { # Success means all 3 colors appear
success <- 1
}
cat("success =", success, "\n")success = 0
Now watch 10 complete repetitions.
R <- 10
success.total <- 0
for (i in 1:R) {
x <- sample(colors, 3, replace = TRUE,
prob = probs)
success <- 0
if (length(unique(x)) == 3) {
success <- 1
}
success.total <- success.total + success
cat("rep =", i,
"x =", x,
"success =", success,
"total =", success.total, "\n")
}rep = 1 x = blue blue blue success = 0 total = 0
rep = 2 x = green blue green success = 0 total = 0
rep = 3 x = green blue green success = 0 total = 0
rep = 4 x = blue green green success = 0 total = 0
rep = 5 x = blue red green success = 1 total = 1
rep = 6 x = green green blue success = 0 total = 1
rep = 7 x = green blue blue success = 0 total = 1
rep = 8 x = blue green green success = 0 total = 1
rep = 9 x = blue green green success = 0 total = 1
rep = 10 x = green green green success = 0 total = 1
p.hat <- success.total / R
cat("p.hat =", p.hat, "\n")p.hat = 0.1
Now increase the number of repetitions without printing every repetition.
R <- 10000
success.total <- 0
for (i in 1:R) {
x <- sample(colors, 3, replace = TRUE,
prob = probs)
if (length(unique(x)) == 3) {
success.total <- success.total + 1
}
}
p.hat <- success.total / R
cat("p.hat =", p.hat, "\n")p.hat = 0.1832
Our theoretical prediction is
\[ p=P(\text{getting all three colors}). \]
Our simulation gives \(\hat p\).
If \(p\) is known, compare the two. Otherwise, use a large number of repetitions to approximate \(p\).
1. Theoretical Prediction
\[ p=P(\text{getting all three colors}). \]
2. Numerical Simulation
3. Comparison
Compare \(\hat p\) with \(p\). If \(p\) is not known numerically, use \(\hat p\) as its numerical approximation.
The important new lesson is
\[ \boxed{\text{the simulation must reproduce the probabilities in the experiment}}. \]
Running the wrong experiment 100,000 times doesn’t fix it. It just gives us a very precise answer to the wrong question.
A bag contains
We randomly select four balls.
Question: What is the probability that all four selected balls are red?
Usually, if we “select four balls from a bag,” we mean that we do not put each ball back before selecting the next one. This is called sampling without replacement.
\[ p=P(\text{success}), \]
where success means selecting four red balls.
First create the bag.
bag <- c(rep("red", 8), rep("blue", 6)) # Create 8 red and 6 blue balls
cat("bag =", bag, "\n")bag = red red red red red red red red blue blue blue blue blue blue
Now select four balls.
x <- sample(bag, 4, replace = FALSE) # Sample without replacement
cat("x =", x, "\n")x = red blue blue red
success <- 0
if (sum(x == "red") == 4) { # Success means all 4 are red
success <- 1
}
cat("success =", success, "\n")success = 0
Now watch 10 repetitions.
R <- 10
success.total <- 0
for (i in 1:R) {
x <- sample(bag, 4, replace = FALSE)
success <- 0
if (sum(x == "red") == 4) {
success <- 1
}
success.total <- success.total + success
cat("rep =", i,
"x =", x,
"success =", success,
"total =", success.total, "\n")
}rep = 1 x = red red blue blue success = 0 total = 0
rep = 2 x = red blue blue red success = 0 total = 0
rep = 3 x = red blue red red success = 0 total = 0
rep = 4 x = red blue blue red success = 0 total = 0
rep = 5 x = red blue red red success = 0 total = 0
rep = 6 x = red red blue red success = 0 total = 0
rep = 7 x = blue blue red red success = 0 total = 0
rep = 8 x = blue blue red red success = 0 total = 0
rep = 9 x = blue blue red blue success = 0 total = 0
rep = 10 x = blue blue red red success = 0 total = 0
p.hat <- success.total / R
cat("p.hat =", p.hat, "\n")p.hat = 0
The important new piece of R is
replace = FALSEIt tells R that once a ball has been selected, it cannot be selected again in the same repetition.
If instead we wrote
x <- sample(bag, 4, replace = TRUE) # Put each ball back before the next drawwe would be simulating a different experiment.
We could repeat that wrong experiment 10 million times and get a very stable answer. It would still be the answer to the wrong question.
Now use many repetitions.
R <- 10000
success.total <- 0
for (i in 1:R) {
x <- sample(bag, 4, replace = FALSE)
if (sum(x == "red") == 4) {
success.total <- success.total + 1
}
}
p.hat <- success.total / R
cat("p.hat =", p.hat, "\n")p.hat = 0.0709
Our theoretical prediction is
\[ p=P(\text{selecting four red balls without replacement}). \]
Our simulation gives \(\hat p\).
1. Theoretical Prediction
\[ p=P(\text{selecting four red balls without replacement}). \]
2. Numerical Simulation
3. Comparison
Compare \(\hat p\) with \(p\). If \(p\) is not calculated analytically, use \(\hat p\) as its numerical approximation.
The general lesson is
\[ \boxed{\text{the simulated experiment must match the experiment we want to study}}. \]
More repetitions reduce randomness in our numerical answer. They cannot fix a simulation of the wrong experiment.
Sometimes one repetition is a sequence of steps, and what happens later depends on what happened earlier.
There are four boxes. One contains a prize.
Question: What is the probability of winning if you switch?
Your first choice contains the prize with probability \(1/4\). Therefore, your first choice is wrong with probability \(3/4\).
Whenever the first choice is wrong, switching takes you to the prize.
So
\[ p=P(\text{success})=\frac34. \]
Number the boxes from 1 to 4.
boxes <- 1:4Randomly place the prize and make a first choice.
prize <- sample(boxes, 1) # Randomly place the prize
choice <- sample(boxes, 1) # Randomly choose one box
cat("prize =", prize, "\n")prize = 1
cat("first choice =", choice, "\n")first choice = 3
Now the host opens two boxes. Which boxes the host can open depends on what happened earlier.
can.open <- setdiff(boxes, c(choice, prize)) # Boxes the host is allowed to open
opened <- sample(can.open, 2)
cat("opened by host =", opened, "\n")opened by host = 2 4
Switch to the one other unopened box.
switch.to <- setdiff(boxes, c(choice, opened))
cat("switch to =", switch.to, "\n")switch to = 1
success <- 0
if (switch.to == prize) {
success <- 1
}
cat("success =", success, "\n")success = 1
Now watch 10 complete games.
R <- 10
success.total <- 0
for (i in 1:R) {
prize <- sample(boxes, 1)
choice <- sample(boxes, 1)
can.open <- setdiff(boxes, c(choice, prize))
opened <- sample(can.open, 2)
switch.to <- setdiff(boxes, c(choice, opened))
success <- 0
if (switch.to == prize) {
success <- 1
}
success.total <- success.total + success
cat("rep =", i,
"prize =", prize,
"choice =", choice,
"open =", opened,
"switch =", switch.to,
"success =", success,
"total =", success.total, "\n")
}rep = 1 prize = 1 choice = 4 open = 3 2 switch = 1 success = 1 total = 1
rep = 2 prize = 3 choice = 3 open = 2 4 switch = 1 success = 0 total = 1
rep = 3 prize = 1 choice = 2 open = 4 3 switch = 1 success = 1 total = 2
rep = 4 prize = 3 choice = 4 open = 2 1 switch = 3 success = 1 total = 3
rep = 5 prize = 1 choice = 1 open = 3 4 switch = 2 success = 0 total = 3
rep = 6 prize = 3 choice = 4 open = 1 2 switch = 3 success = 1 total = 4
rep = 7 prize = 1 choice = 3 open = 4 2 switch = 1 success = 1 total = 5
rep = 8 prize = 2 choice = 4 open = 3 1 switch = 2 success = 1 total = 6
rep = 9 prize = 1 choice = 2 open = 4 3 switch = 1 success = 1 total = 7
rep = 10 prize = 4 choice = 3 open = 2 1 switch = 4 success = 1 total = 8
p.hat <- success.total / R
cat("p.hat =", p.hat, "\n")p.hat = 0.8
With only 10 repetitions, \(\hat p\) may be some distance from 0.75. Now use many repetitions without printing every game.
R <- 10000
success.total <- 0
for (i in 1:R) {
prize <- sample(boxes, 1)
choice <- sample(boxes, 1)
can.open <- setdiff(boxes, c(choice, prize))
opened <- sample(can.open, 2)
switch.to <- setdiff(boxes, c(choice, opened))
if (switch.to == prize) {
success.total <- success.total + 1
}
}
p.hat <- success.total / R
cat("p.hat =", p.hat, "\n")p.hat = 0.7554
Compare
\[ \underbrace{p=0.75}_{\text{theoretical prediction}} \qquad\text{with}\qquad \underbrace{\hat p}_{\text{numerical simulation}}. \]
1. Theoretical Prediction
\[ p=P(\text{success})=\frac34. \]
2. Numerical Simulation
3. Comparison
Compare \(\hat p\) with
\[ p=\frac34. \]
With a sufficiently large \(R\), the two should be close.
The new idea here is
\[ \boxed{\text{later steps in one repetition can depend on earlier outcomes}}. \]
A Monte Carlo experiment can therefore be much more than repeatedly drawing numbers from a fixed list.
Later we might generate one variable, use it to generate another, estimate something from the simulated data, and record the result.
The procedure gets more complicated. The basic idea does not.
Let’s put everything together.
When you are asked to describe a Monte Carlo algorithm, your answer should contain three parts.
State what theory predicts.
For a probability problem,
\[ p=P(\text{success}). \]
If the exact value of \(p\) is easy or given, report it.
If calculating \(p\) requires probability tools that we are not using, leave it as \(p\). Calculating the exact probability is not the point of the exercise.
Write a numbered algorithm.
It should tell us:
For probability problems, the final step will usually be
\[ \hat p= \frac{\text{number of successes}}{R}. \]
A good algorithm describes what to do, not particular R commands.
Explain how the theoretical prediction and numerical simulation are compared:
\[ \boxed{p \quad\text{vs.}\quad \hat p}. \]
If \(p\) is known, a good Monte Carlo simulation with sufficiently large \(R\) should produce a \(\hat p\) close to \(p\).
If \(p\) is not known numerically, \(\hat p\) gives us a numerical approximation.
So remember:
\[ \boxed{\text{Theoretical Prediction}} \;\longrightarrow\; \boxed{\text{Numerical Simulation}} \;\longrightarrow\; \boxed{\text{Comparison}} \]
Together, these make a complete Monte Carlo algorithm.
The numerical simulation by itself is not a complete Monte Carlo algorithm.
For a new problem, ask yourself:
Once those questions are clear, write the complete algorithm.
Now try the probability questions in the practice set. They include coin tosses, repeated tosses, unequal probabilities, sampling without replacement, repeated wins, basketball shots, Scrabble tiles, and Monty Hall.
For each problem, write a complete Monte Carlo algorithm:
1. Theoretical Prediction
\[ p=P(\text{success}). \]
2. Numerical Simulation
Write the numbered steps in words.
3. Comparison
Explain how you would compare \(p\) and \(\hat p\).
R code is not required for the algorithm.
So far, we have used Monte Carlo to study one probability.
For example,
\[ P(\text{roll a 4}) \]
or
\[ P(\text{get exactly two 4s}). \]
But suppose instead we want the probabilities of all possible outcomes.
For six die rolls, we might ask:
\[ P(\text{0 fours}),\; P(\text{1 four}),\; P(\text{2 fours}),\ldots, P(\text{6 fours}). \]
Now we are no longer interested in one probability.
We are interested in a distribution.
That is where we go next.