The Dual Problem
Review the function dual() in the Practice Exercises of this Chapter. Modify the function as follows:
- Add a parameter
abethat gives the probability for Abe to hit when he shoots, and a parameterbothat gives the chance for Bo to hit when he shoots. the probabilities should be expressed as numbers between 0 and 1. (Thus, a 30% chance of hitting is 0.30.) - Make the function estimate the expected value number of shots taken in a dual, rather than the chance for Abe to win.
When you have your function working, use it to estimate the expected number of shots when:
- Abe’s chance of hitting is 50 percent and Bo’s chance if 50%;
- Abe’s chance of hitting is 20% and Bo’s chance of hitting is 25%.
In each simulation, use one hundred thousand repetitions and a seed that you choose.
Hints
The hint comes in three parts.
Study the Dual Code
First, understand deeply the code for the original dual() function:
dual <- function(reps = 10000, seed = NULL) {
if (!is.null(seed)) {
set.seed(seed)
}
# set up logical vector to store results of each simulation:
abeWins <- logical(reps)
for (i in 1:reps) {
dualing <- TRUE
shotNumber <- 1
while (dualing) {
# if i is an odd number, then Abe is shooting:
abeToShoot <- shotNumber %% 2 == 1
# probability of hitting depends on who is shooting:
hitProb <- ifelse(abeToShoot, 0.4, 0.6)
# shooter takes a shot:
resultOfShot <- sample(c("hit", "miss"),
size = 1,
prob = c(hitProb, 1 - hitProb))
if (resultOfShot == "hit") {
abeWins[i] <- ifelse(abeToShoot, TRUE, FALSE)
dualing <- FALSE
}
shotNumber <- shotNumber + 1
}
}
# count up how many times abe won, divide by number of plays,
# and return:
sum(abeWins)/reps
}In addition to reading the code carefully and reviewing all functions and operators used (for example, the %% mod arithmetic operator from Chapter 2), it can help to run the function for a very small number of reps, in debug mode:
Switch to Estimating Expected Number of Shots
The original dual() function estimates the probability that Abe will win. That’s why it sets up a logical vector to hold the results of each of the reps simulated duals:
Since we want to estimate the expected number of shots taken in a dual, we have to set up a different sort of results vector: a numerical vector that is reps long. Give this vector a meaningful name, such as shots:
Now look at the line the original function where we record in the abeWins vector whether or not Abe wins the dual that just finished:
You will need to replace that line with a line that stores the number of shots taken in the just-finished dual into the shots vector.
Introduce the abe and bo Parameters
The code for the original dual problem assumes that Abe has a 40% chance of hitting his target and that Bo has a 60% chance of hitting his target. You need to add the two extra parameters abe and bo to the definition of the function, and then you have to look into the body to decide which specific numbers have to be replaced with parameters.