Suppose we want to simulate 3 tosses of a fair coin to find $P(X=1)$.
What my teacher has done in R is this,
- sample 3 tosses.
- replicate (1) $n$ times.
- count the number of heads $n_H$ in each of $n$ tosses. The result would be a list.
- count how many times 1 appear in the list.
- divide it by $n$.
My question is, where did he find this technique?
If you are interested, the following is the R source code sample:
n_toss = 3; # Number of Tosses
n_trial = 10000; # Number of Trials
mySamples <- replicate(n_trial, {mySamples<- sample(c(1,0), n_toss, replace = T, prob = c(0.5,0.5))})
headCountList <- colSums(mySamples); # this indicates the number of heads
# the headCount is 1, that is X==1.
probOfCoinToss <- length(which(headCountList == 1))/n_trial;
probOfCoinToss
[1] 0.3767
EX<- sum(headCountList)/n_trial
EX
[1] 1.5024
This is formally known as Monte Carlo sampling