Simulation and Exact Probability
A fair six-sided die is rolled six times. If the face numbered "j" is the outcome on the j-th roll we say "a match has occurred." The experiment is declared "success" if at least one match occurs during the six trials.- Simulate this experiment 500 times, and evaluate the proportion of "success" event.
- Compute the exact probability of "success,"
exact.prob = 1 - (5/6)^6
and compare it with the evaluation via simulation.
Here we have to simulate a slightly complicated experiment: Generate 6 trials of rolling a fair six-sided die, and find out whether the j-th attempt results in the exact same number j. We can write all the tasks of experiment by defining a function
is.matched()
The function is.match(outcome) returns the value "1" if at least one match is found in "outcome" of the six trials. Otherwise, it returns "0."
is.matched = function(outcome){ match.status = 0; for(j in 1:6){ if(outcome[j] == j) match.status = 1; } match.status }
The function sample(6,size=6,replace=T) randomly generates numbers drawn from 1 to 6 for 6 times (size=6). Then use it to simulate the experiment repeatedly for n = 500 times. It evaluates the proportion of "success" event, and creates "success.rate"
n = 500; success = NULL; success.rate = NULL; prob = rep(1/6,6); for(i in 1:n){ outcome = sample(6,size=6,replace=T); success[i] = is.matched(outcome); success.rate[i] = mean(success); }
Here we use plot() and lines() to visualize the success rate in series. Compute the exact probability for "winning the game," and compare it with the evaluation via simulation.
exact.prob = 1 - (5/6)^6; plot(c(1,n), rep(exact.prob,2), ylab='Fraction of successes', type='l', lty=2); lines(1:n, success.rate, col='blue'); print(success.rate[n])
Sample R code. You can download diegame.R, and run it by
source(file.choose())where file.choose() lets you choose the R code.
Programming Note. Here the results of repeated experiment are stored in the data variable
successwhere the event of successful match is indicated by 1; otherwise it is 0.
© TTU Mathematics