Pg 13, E4
In raquetball, a player continues to serve as long as she is winning; a point is scored only when a player is serving and wins the volley. The first player to win 21 points wins the game. Assume that you serve first and have a probability 0.6 of winning a volley when you serve and probability 0.5 when your opponent serves. Estimate, by simulation, the probability that you will win a game.
Raquetball <- function() {
#Tracks who the current server, used to assign points
Serving <- 1
#Probabilities
Prob_win_serve_1st <- 0.6
Prob_win_serve_2nd <- 0.5
#1 = I win. 0 = Opponent wins
outcomes <- c(1,0) # 1, 0 will be used to count how many times I win in n games
#tracking points
Score_mine <- 0
Score_Opponent <- 0
#game loops until someone reaches 21 points
while (Score_mine < 21 & Score_Opponent < 21) {
#If opponent serves, use P = 0.5
if (Serving == 0) {
#probabilities <- c(Prob_win_serve_2nd, 1-Prob_win_serve_2nd)
who_won <- sample(outcomes, 1, prob = c(0.5,0.5))
#If opponent wins, they get a point, otherwise I serve
if (who_won == 0) {
Score_Opponent <- Score_Opponent + 1
} else {
Serving <- 1
}
} else {
#If I serve, use P = 0.6
#probabilities <- c(Prob_win_serve_1st, 1- Prob_win_serve_1st)
who_won <- sample(outcomes, 1, prob = c(0.6,0.4))
#If I win,add a point to my total, otherwise opponent serves
if (who_won == 1) {
Score_mine <- Score_mine + 1
} else {
Serving <- 0
}
}
}
if (Score_mine == 21) {
return(1)
}
else {
return(0)
}
}
Let’s see the chance of winning a game in 5000 games
count <- c()
simulations <- 5000
for (i in seq(simulations)) {
game <- Raquetball()
count <- c(count, game)
}
Prob_win <- sum(count) / length(count)
cat("The probability to win in ", simulations, " games is: ", Prob_win )
## The probability to win in 5000 games is: 0.83