A Monte Carlo simulation can show us the distribution directly. Instead of recording only whether each repetition is a success or failure, we record the value of \(X\) from every repetition.
2.2 A complete Monte Carlo algorithm for a distribution
Suppose again that we roll a fair six-sided die and define
\[
X=\text{number showing on the die}.
\]
The possible values of \(X\) are
\[
1,2,3,4,5,6.
\]
A complete Monte Carlo algorithm still has the same three parts:
These probabilities describe the theoretical distribution of \(X\).
We do not need to calculate their numerical values unless the problem asks us to. If they are not known, leave them as \(p_1,p_2,\ldots,p_{11}\).
2. Numerical Simulation
Start with one repetition.
dice <-sample(1:6, 2, replace =TRUE) # Roll two fair six-sided dicecat("dice =", dice, "\n") # Print the two outcomes
dice = 1 3
x <-sum(dice) # Add the two dice to get Xcat("X =", x, "\n") # Print the value of X
X = 4
This is one repetition of the experiment.
Now we need a counter for every possible value of \(X\).
x.values <-2:12# List all possible values of Xcount <-rep(0, length(x.values)) # Start one counter at 0 for each value of Xcat("X values =", x.values, "\n") # Print the possible values of X
X values = 2 3 4 5 6 7 8 9 10 11 12
cat("counts =", count, "\n") # Print the starting counters
counts = 0 0 0 0 0 0 0 0 0 0 0
Suppose a repetition produces a value of \(X\). We need to add 1 to the counter corresponding to that value.
j <-which(x.values == x) # Find where the observed X appears in x.valuescount[j] <- count[j] +1# Add 1 to the counter for that value of Xcat("counts =", count, "\n") # Print the updated counters
counts = 0 0 1 0 0 0 0 0 0 0 0
Now watch 10 repetitions.
R <-10# Number of repetitionsx.values <-2:12# Possible values of Xcount <-rep(0, length(x.values)) # Reset all counters to 0cat("X values =", x.values, "\n") # Show which value each counter represents
X values = 2 3 4 5 6 7 8 9 10 11 12
# Repeat the experiment R timesfor (i in1:R) { dice <-sample(1:6, 2, replace =TRUE) # Roll two fair dice x <-sum(dice) # Calculate their sum j <-which(x.values == x) # Find the counter corresponding to X count[j] <- count[j] +1# Add 1 to that countercat("rep =", i,"dice =", dice,"X =", x, "\n") # Show the dice and the value of Xcat("counts =", count, "\n") # Show all counters after this repetition}
After 10 repetitions, divide each counter by \(R\).
p.hat <- count / R # Convert the counters into simulated probabilitiescat("X =", x.values, "\n") # Print the possible values of X
X = 2 3 4 5 6 7 8 9 10 11 12
cat("P.hat =", round(p.hat, 3), "\n") # Print the simulated probabilities
P.hat = 0 0 0.1 0.1 0 0.3 0.1 0.2 0.2 0 0
With only 10 repetitions, the simulated distribution will be quite rough.
Now use many repetitions.
R <-10000# Use many repetitions for a better numerical estimatex.values <-2:12# Possible values of Xcount <-rep(0, length(x.values)) # Reset all counters to 0for (i in1:R) { dice <-sample(1:6, 2, replace =TRUE) # Roll two fair dice x <-sum(dice) # Calculate X j <-which(x.values == x) # Locate the counter for X count[j] <- count[j] +1# Update that counter}p.hat <- count / R # Estimate the probability of each possible valuecat("X =", x.values, "\n")
The graph below puts the numerical simulation and theoretical prediction on the same figure. The bars show the simulated probabilities \(\hat p_1,\ldots,\hat p_{11}\); the points and line show the theoretical probabilities \(p_1,\ldots,p_{11}\). We do not need to report the numerical values of the theoretical probabilities.
Figure 2.1: Simulated and theoretical distributions of X, the sum of two fair dice. Bars show the simulated probabilities; points and the line show the theoretical prediction.
With a sufficiently large \(R\), the simulated distribution should be close to the theoretical distribution.
So far, our random variables have taken only a finite number of possible values. We call these discrete random variables.
Now suppose
\[
X\sim U(2,5).
\]
This means that \(X\) can take any value between 2 and 5. For example,
\[
2.13,\qquad 3.7,\qquad 4.982
\]
are all possible values.
There are infinitely many possible values between 2 and 5. We call \(X\) a continuous random variable.
For a continuous random variable, we describe the distribution using a density function
\[
f(x).
\]
The density tells us where values of \(X\) tend to occur. Larger values of \(f(x)\) mean that observations are more concentrated around that part of the distribution.
Just as we did not always need to calculate the exact probability \(p\) in Chapter 1, we do not always need to know the exact formula for \(f(x)\). If it is not known, simply leave it as \(f(x)\).
For a uniform distribution, the density is flat: values between 2 and 5 are spread evenly across the interval.
1. Theoretical Prediction
\[
X\sim U(2,5).
\]
Let \(f(x)\) denote the theoretical density. For a uniform distribution, \(f(x)\) is flat between 2 and 5. We do not need to calculate its exact value.
2. Numerical Simulation
R can generate a random draw from a uniform distribution using runif().
Start with one draw.
x <-runif(1, min =2, max =5) # Generate 1 random value from U(2,5)cat("X =", round(x, 3), "\n") # Print the simulated value
X = 3.233
Now watch 10 repetitions.
R <-10# Number of repetitionsfor (i in1:R) { x <-runif(1, min =2, max =5) # Generate one value from U(2,5)cat("rep =", i,"X =", round(x, 3), "\n") # Print the value generated in this repetition}
rep = 1 X = 2.024
rep = 2 X = 3.859
rep = 3 X = 3.917
rep = 4 X = 3.359
rep = 5 X = 3.81
rep = 6 X = 3.864
rep = 7 X = 3.916
rep = 8 X = 2.193
rep = 9 X = 3.507
rep = 10 X = 3.729
With only 10 observations, it is hard to see the shape of the distribution.
Now generate many observations and save them.
R <-10000# Use many repetitionsx <-rep(0, R) # Create space to save all R simulated valuesfor (i in1:R) { x[i] <-runif(1, min =2, max =5) # Generate X and save it in position i}
We now have \(R\) simulated values of \(X\) saved in x.
3. Comparison
Compare the simulated distribution with the theoretical density \(f(x)\). The histogram below shows the numerical simulation, while the line shows the theoretical prediction. R calculates \(f(x)\) for us with dunif().
hist(x,probability =TRUE, # Scale the histogram so it can be compared with a densityxlab ="X",main ="")curve(dunif(x, min =2, max =5), # Ask R for the theoretical density f(x)from =2, to =5,add =TRUE, # Add the theoretical density to the histogramlwd =2)
Figure 2.2: Simulated and theoretical distributions of X ~ U(2,5). The histogram shows the numerical simulation; the line shows the theoretical density f(x).
With sufficiently many repetitions, the histogram should have approximately the same shape as the theoretical distribution.
Complete Monte Carlo Algorithm
1. Theoretical Prediction
\[
X\sim U(2,5),
\]
with theoretical density \(f(x)\). If the exact formula is not known, leave it as \(f(x)\).
2. Numerical Simulation
Generate one value \(X\) from \(U(2,5)\).
Save the value of \(X\).
Repeat steps 1–2 \(R\) times.
Plot the simulated values using a histogram.
3. Comparison
Compare the simulated histogram with the theoretical density \(f(x)\).
The important distinction is:
\[
\boxed{\text{Discrete distribution: count how often each value occurs}}
\]
\[
\boxed{\text{Continuous distribution: save the values and examine their histogram}}.
\]
2.5 Different distributions, same idea
The uniform distribution is only one possible continuous distribution.
Other distributions have different shapes. For example, a chi-square distribution is typically concentrated near smaller values and has a long right tail. An \(F\) distribution is also right-skewed, while a Student \(t\) distribution is symmetric.
The important point is that the Monte Carlo procedure does not change.
Suppose
\[
X\sim\chi^2(6).
\]
Let \(f(x)\) denote the theoretical density of \(X\). We do not need to know the exact formula for \(f(x)\).
1. Theoretical Prediction
\[
X\sim\chi^2(6),
\]
with theoretical density \(f(x)\).
2. Numerical Simulation
R generates a chi-square random variable using rchisq().
Start with one draw.
x <-rchisq(1, df =6) # Generate 1 value from a chi-square distribution with 6 degrees of freedomcat("X =", round(x, 3), "\n") # Print the simulated value
X = 9.931
Now watch 10 repetitions.
R <-10# Number of repetitionsfor (i in1:R) { x <-rchisq(1, df =6) # Generate one value from chi-square(6)cat("rep =", i,"X =", round(x, 3), "\n") # Print the value generated in this repetition}
rep = 1 X = 1.357
rep = 2 X = 10.163
rep = 3 X = 1.608
rep = 4 X = 8.442
rep = 5 X = 5.424
rep = 6 X = 5.284
rep = 7 X = 5.86
rep = 8 X = 2.034
rep = 9 X = 9.902
rep = 10 X = 3.647
To see the distribution, generate many observations and save them.
R <-10000# Use many repetitionsx <-rep(0, R) # Create space for all R simulated valuesfor (i in1:R) { x[i] <-rchisq(1, df =6) # Generate X and save it in position i}
We now have \(R\) simulated values of \(X\) saved in x.
3. Comparison
Compare the simulated distribution with the theoretical density \(f(x)\). The histogram below shows the numerical simulation, while the line shows the theoretical prediction. R calculates \(f(x)\) for us with dchisq().
hist(x,probability =TRUE, # Scale the histogram so it can be compared with a densityxlab ="X",main ="")curve(dchisq(x, df =6), # Ask R for the theoretical density f(x)from =0, to =max(x),add =TRUE, # Add the theoretical density to the histogramlwd =2)
Figure 2.3: Simulated and theoretical distributions of X ~ chi-square(6). The histogram shows the numerical simulation; the line shows the theoretical density f(x).
With sufficiently many repetitions, the histogram should have approximately the same shape as the theoretical distribution. The shape differs from the uniform distribution, but the Monte Carlo procedure is the same.
Complete Monte Carlo Algorithm
1. Theoretical Prediction
\[
X\sim\chi^2(6),
\]
with theoretical density \(f(x)\). If the exact formula is not known, leave it as \(f(x)\).
2. Numerical Simulation
Generate one value \(X\) from \(\chi^2(6)\).
Save the value of \(X\).
Repeat steps 1–2 \(R\) times.
Plot the simulated values using a histogram.
3. Comparison
Compare the simulated histogram with the theoretical density \(f(x)\).
Only the command used to generate \(X\) changes across distributions. For example:
runif(1, min =2, max =5) # Uniform distributionrchisq(1, df =6) # Chi-square distributionrf(1, df1 =5, df2 =15) # F distributionrt(1, df =8) # Student t distribution
The distribution changes. The Monte Carlo logic does not:
A distribution tells us where values of \(X\) tend to occur. Sometimes we want to summarize that information with an interval.
A 95% probability interval is an interval \([a,b]\) such that
\[
P(a<X<b)=0.95.
\]
If you do not know the numerical values of \(a\) and \(b\), just leave them as \(a\) and \(b\). You do not need to calculate the endpoints unless the problem asks you to.
Suppose again that
\[
X\sim U(2,5).
\]
For this example, use the 95% probability interval
\[
[a,b]=[2.075,4.925].
\]
The figure below shows the distribution and the probability interval \([a,b]\).
Figure 2.4: A 95% probability interval for X ~ U(2,5). The interval [a,b] contains 95% of the theoretical probability.
1. Theoretical Prediction
Let \([a,b]\) be the 95% probability interval. Then
\[
P(a<X<b)=0.95.
\]
For this example,
\[
P(2.075<X<4.925)=0.95.
\]
2. Numerical Simulation
Generate one value of \(X\).
x <-runif(1, min =2, max =5) # Generate 1 value from U(2,5)cat("X =", round(x, 3), "\n") # Print the simulated value
X = 4.247
Now check whether \(X\) is inside the probability interval.
a <-2.075# Lower endpoint of the intervalb <-4.925# Upper endpoint of the intervalsuccess <-0# Start the success indicator at 0if ((x > a) && (x < b)) { # Check whether X is inside the interval success <-1# Count it as a success if it is inside}cat("success =", success, "\n")
success = 1
Here, success means that the simulated value falls inside the probability interval.
Now watch 10 repetitions.
R <-10# Number of repetitionssuccess.total <-0# Start the success counter at 0for (i in1:R) { x <-runif(1, min =2, max =5) # Generate one value from U(2,5) success <-0# Start this repetition as a failureif ((x > a) && (x < b)) { # Check whether X is inside the interval success <-1# Change to success if X is inside } success.total <- success.total + success # Update the total number of successescat("rep =", i,"X =", round(x, 3),"success =", success,"total =", success.total, "\n") # Show what happened in this repetition}
rep = 1 X = 2.264 success = 1 total = 1
rep = 2 X = 2.198 success = 1 total = 2
rep = 3 X = 4.055 success = 1 total = 3
rep = 4 X = 4.677 success = 1 total = 4
rep = 5 X = 3.078 success = 1 total = 5
rep = 6 X = 3.933 success = 1 total = 6
rep = 7 X = 2.633 success = 1 total = 7
rep = 8 X = 2.256 success = 1 total = 8
rep = 9 X = 3.509 success = 1 total = 9
rep = 10 X = 3.196 success = 1 total = 10
With only 10 repetitions, the fraction inside the interval may be some distance from 0.95.
Now use many repetitions.
R <-10000# Use many repetitionssuccess.total <-0# Reset the success counterfor (i in1:R) { x <-runif(1, min =2, max =5) # Generate one value from U(2,5)if ((x > a) && (x < b)) { # Check whether X is inside the interval success.total <- success.total +1 }}p.hat <- success.total / R # Fraction of simulated values inside the intervalcat("p.hat =", p.hat, "\n")
p.hat = 0.9535
3. Comparison
The theoretical prediction is
\[
p=0.95.
\]
The numerical simulation gives
\[
\hat p
=
\frac{\text{number of simulated values inside }[a,b]}{R}.
\]
Compare
\[
\hat p\approx 0.95.
\]
Complete Monte Carlo Algorithm
1. Theoretical Prediction
Let \([a,b]\) be the probability interval. For a 95% probability interval,
\[
P(a<X<b)=0.95.
\]
If the endpoints are not known numerically, leave them as \(a\) and \(b\).
2. Numerical Simulation
Generate one value \(X\) from the theoretical distribution.
If \(X\) is inside \([a,b]\), count the repetition as a success.
Repeat steps 1–2 \(R\) times.
Calculate
\[
\hat p
=
\frac{\text{number of successes}}{R}.
\]
3. Comparison
Compare
\[
\hat p\approx 0.95.
\]
2.7 Mean as the center of a distribution
A distribution tells us where values of \(X\) tend to occur.
One useful way to summarize a distribution is to describe its center.
The mean, also called the expectation, is one measure of the center of a distribution. We write
\[
\mu=E(X).
\]
If you do not know the numerical value of \(\mu\), just leave it as \(\mu\). You do not need to calculate it unless the problem asks you to.
Suppose again that
\[
X\sim U(2,5).
\]
The uniform distribution is symmetric between 2 and 5, so its center is
\[
\mu=3.5.
\]
The figure below shows the distribution and its center.
Figure 2.5: The distribution of X ~ U(2,5) and its mean. The vertical line at 3.5 marks the center of the distribution.
1. Theoretical Prediction
Let
\[
\mu=E(X)
\]
denote the theoretical mean.
For this example,
\[
\mu=3.5.
\]
2. Numerical Simulation
Start with one draw.
x <-runif(1, min =2, max =5) # Generate 1 value from U(2,5)cat("X =", round(x, 3), "\n") # Print the simulated value
X = 3.225
Now watch 10 repetitions and save every simulated value.
R <-10# Number of repetitionsx <-rep(0, R) # Create space to save the simulated valuesfor (i in1:R) { x[i] <-runif(1, min =2, max =5) # Generate X and save it in position icat("rep =", i,"X =", round(x[i], 3), "\n") # Print the value generated in this repetition}
rep = 1 X = 3.787
rep = 2 X = 4.514
rep = 3 X = 4.726
rep = 4 X = 4.749
rep = 5 X = 3.716
rep = 6 X = 2.62
rep = 7 X = 3.337
rep = 8 X = 3.532
rep = 9 X = 2.402
rep = 10 X = 2.602
mu.hat <-mean(x) # Average the 10 simulated valuescat("mu.hat =", round(mu.hat, 3), "\n")
mu.hat = 3.599
With only 10 repetitions, \(\hat\mu\) may be some distance from \(\mu\).
Now use many repetitions.
R <-10000# Use many repetitionsx <-rep(0, R) # Create space for all simulated valuesfor (i in1:R) { x[i] <-runif(1, min =2, max =5) # Generate X and save it}mu.hat <-mean(x) # Average all simulated valuescat("mu.hat =", round(mu.hat, 3), "\n")
mu.hat = 3.497
The Law of Large Numbers
As the number of independent repetitions becomes large, the average of the simulated values tends to get closer to the theoretical mean:
\[
\hat\mu\longrightarrow\mu.
\]
This result is called the Law of Large Numbers.
In Monte Carlo simulations, the Law of Large Numbers explains why the numerical estimate generally improves as the number of repetitions increases.
The same idea was already at work in Chapter 1. A success indicator is a random variable that equals 1 for success and 0 for failure. Its mean is the probability of success. That is why \(\hat p\) also generally improves as \(R\) increases.
denote the theoretical mean. If its numerical value is not known, leave it as \(\mu\).
2. Numerical Simulation
Generate one value \(X\) from the theoretical distribution.
Save the value of \(X\).
Repeat steps 1–2 \(R\) times.
Average the simulated values to obtain \(\hat\mu\).
3. Comparison
Compare
\[
\hat\mu\approx\mu.
\]
2.8 Variance as spread around the center
The mean tells us where a distribution is centered.
But two distributions can have the same center and look very different. One can be tightly concentrated around the center, while another can be much more spread out.
The variance describes this spread.
The idea is illustrated below.
Figure 2.6: Two uniform distributions with the same mean but different variances. Both are centered at 3.5, but U(2,5) is more spread out than U(3,4).
Suppose \(X\) has mean \(\mu\).
The distance of one observation from the center is
\[
X-\mu.
\]
Some observations are above the center and some are below it. If we simply averaged these distances, positive and negative values would tend to cancel.
Instead, we square the distance:
\[
(X-\mu)^2.
\]
The variance is the average squared distance from the center.
We write
\[
\sigma^2=\operatorname{Var}(X).
\]
A larger variance means that values of \(X\) tend to be farther from the center.
If you do not know the numerical value of \(\sigma^2\), just leave it as \(\sigma^2\). You do not need to calculate it unless the problem asks you to.
1. Theoretical Prediction
Suppose again that
\[
X\sim U(2,5).
\]
Its center is
\[
\mu=3.5.
\]
Let
\[
\sigma^2=\operatorname{Var}(X)
\]
denote its theoretical variance. For this example,
\[
\sigma^2=0.75.
\]
As before, if the theoretical value is not known in another problem, it is enough to leave it as \(\sigma^2\).
2. Numerical Simulation
Start with one draw and calculate its squared distance from the mean.
mu <-3.5# Mean, or center, of U(2,5)x <-runif(1, min =2, max =5) # Generate 1 value from U(2,5)sq.dev <- (x - mu)^2# Calculate the squared distance from the meancat("X =", round(x, 3), "\n")
X = 2.18
cat("sq.dev =", round(sq.dev, 3), "\n")
sq.dev = 1.742
Now watch 10 repetitions and save every value of \(X\).
R <-10# Number of repetitionsx <-rep(0, R) # Create space to save the simulated valuesfor (i in1:R) { x[i] <-runif(1, min =2, max =5) # Generate X and save it sq.dev <- (x[i] - mu)^2# Calculate squared distance from the meancat("rep =", i,"X =", round(x[i], 3),"sq.dev =", round(sq.dev, 3), "\n") # Show the squared distance for this repetition}
rep = 1 X = 3.995 sq.dev = 0.245
rep = 2 X = 2.955 sq.dev = 0.297
rep = 3 X = 4.266 sq.dev = 0.587
rep = 4 X = 2.517 sq.dev = 0.966
rep = 5 X = 3.908 sq.dev = 0.166
rep = 6 X = 2.392 sq.dev = 1.227
rep = 7 X = 3.699 sq.dev = 0.039
rep = 8 X = 2.559 sq.dev = 0.886
rep = 9 X = 3.377 sq.dev = 0.015
rep = 10 X = 3.773 sq.dev = 0.075
sig2.hat <-mean((x - mu)^2) # Average the squared distancescat("sig2.hat =", round(sig2.hat, 3), "\n")
sig2.hat = 0.45
Now use many repetitions.
R <-10000# Use many repetitionsx <-rep(0, R) # Create space for all simulated valuesfor (i in1:R) { x[i] <-runif(1, min =2, max =5) # Generate X and save it}sig2.hat <-mean((x - mu)^2) # Average the squared distances from the meancat("sig2.hat =", round(sig2.hat, 3), "\n")
sig2.hat = 0.755
The Law of Large Numbers applies here too. As \(R\) increases, \(\hat\sigma^2\) generally improves as an estimate of \(\sigma^2\).
What changes is what we record from each repetition and how we summarize it.
Throughout these notes, you do not need to know the numerical value of the theoretical prediction unless the problem asks you to calculate it. If you do not know it, leave it in symbolic form.
Probability
We studied probability in Chapter 1.
If
\[
p=P(\text{success}),
\]
count the number of successful repetitions and calculate \(\hat p\).
If the numerical value of \(p\) is not known, leave it as \(p\).
Compare
\[
\hat p\approx p.
\]
Discrete distribution
Let
\[
p_1,p_2,\ldots,p_k
\]
denote the theoretical probabilities of the possible values. If these probabilities are not known numerically, leave them as \(p_1,p_2,\ldots,p_k\).
For each repetition, record \(X\) and add 1 to the counter corresponding to the observed value. After \(R\) repetitions, calculate
denote the theoretical density. If you do not know the formula for \(f(x)\), leave it as \(f(x)\).
Generate and save the value of \(X\) from each repetition. After many repetitions, plot the simulated values using a histogram.
Compare the histogram with the theoretical density \(f(x)\).
Probability interval
Suppose \([a,b]\) is a probability interval such that
\[
P(a<X<b)=p.
\]
If the endpoints are not known numerically, leave them as \(a\) and \(b\). If the probability is not known numerically, leave it as \(p\).
Count a success whenever \(a<X<b\), calculate \(\hat p\), and compare
\[
\hat p\approx p.
\]
Mean
The mean describes the center of a distribution.
Let
\[
\mu=E(X).
\]
If its numerical value is not known, leave it as \(\mu\).
Generate and save \(R\) values of \(X\), average them to obtain \(\hat\mu\), and compare
\[
\hat\mu\approx\mu.
\]
Variance
The variance describes how spread out a distribution is around its center.
Let
\[
\sigma^2=\operatorname{Var}(X).
\]
If its numerical value is not known, leave it as \(\sigma^2\).
Generate and save \(R\) values of \(X\), calculate their squared distances from the mean, and average those squared distances to obtain \(\hat\sigma^2\).
Compare
\[
\hat\sigma^2\approx\sigma^2.
\]
More repetitions improve Monte Carlo estimates
There is one idea behind all of these simulations.
As the number of Monte Carlo repetitions \(R\) increases, our numerical estimates generally improve.
The Law of Large Numbers explains this result. This is why we often begin with
\[
R=10
\]
to see what the simulation is doing, and then increase to something like
\[
R=10{,}000
\]
to obtain a better numerical estimate.
Before writing an algorithm, ask:
What am I trying to estimate?
Once that is clear, the numerical simulation usually follows naturally.
2.10 Where we go next
So far, one repetition has usually generated one value of a random variable \(X\).
Now suppose instead that one repetition generates an entire sample:
\[
X_1,X_2,\ldots,X_n.
\]
From that sample, calculate the sample mean (also called the sample average)
\[
\bar X
=
\frac{X_1+\cdots+X_n}{n}.
\]
Because the sample is random, \(\bar X\) is random too.
And because we are doing Monte Carlo simulation, we can generate many samples.
For each sample:
Generate \(X_1,\ldots,X_n\).
Calculate \(\bar X\).
Save \(\bar X\).
After repeating this many times, we have one sample mean from each Monte Carlo repetition:
\[
\bar X_1,\bar X_2,\ldots,\bar X_R.
\]
We can then ask:
\[
\boxed{\text{What does the distribution of }\bar X\text{ look like?}}
\]
That question leads us to the Central Limit Theorem.