Simulating Fair Coin Toss in R

5.2k Views Asked by At

I am new to R, I found the theoretical answer but need to learn how to use R for simulation.

Question: Consider tossing three fair coins. Define X as the random variable "number of heads showing when three coins are tossed." Simulate tossing three coins 10,000 times in R. Compute the simulated mean and variance of X.

Thanks for answers.

2

There are 2 best solutions below

3
On

Let $Y_i \sim$ Bernoulli$(p)$, with $p\in(0,1)$ for $i = \{1,2,3\}$.

Then $X = \mathbb{1}_{\{Y_1 = 1\}} + \mathbb{1}_{\{Y_2 = 1\}} + \mathbb{1}_{\{Y_2 = 1\}}$ is the number of heads (success) in three coin tosses.

We have that $EX = 3p$ and $VX = 3p(1-p) = 3(p-p^2)$, if the coin is fair then $p=\frac{1}{2}$ and $EX = 1.5$ and $VX = 0.75$.

This can be simulated in R like this:

n <- 10000; p <- 1/2

Y_1 <- rbinom(n, 1, p)  #Berloulli variable
Y_2 <- rbinom(n, 1, p)  
Y_3 <- rbinom(n, 1, p)

X <- Y_1 + Y_2 + Y_3

mean(X)
var(X) 

Things are quicker if you know that the sum of Berloulli random variables (coin tosses) is a binomial variable, as others have stated.

0
On
n = 3;  p = 1/2
x = rbinom(10000, n, p)
mean(x);  var(x)
[1] 1.5023     # simulated E(X)
[1] 0.7394687  # simulated Var(X)
n*p; n*p*(1-p)
[1] 1.5        # exact E(X)
[1] 0.75       # exact V(X)
1.96*sd(x)/sqrt(10000)
[1] 0.0168545  # 95% margin of simulation error for E(X)

hist(x, prob=T, br=(-1:3)+.5, col="skyblue", main="Simulated PDF of BINOM(3,.5)")
i = 0:3;  pdf=dbinom(i,n,p)
points(i, pdf, pch=19, col="red")

enter image description here