For context 6: In the text, it was shown that if q < p, there is a positive probability that a gambler, starting with a stake of 0 dollars, will never return to the origin. Thus, we will now assume that q ≥ p. Using Exercise 5, show that if a gambler starts with a stake of 0 dollars, then the expected number of times her stake equals M before returning to 0 equals (p/q)M, if q > p and 1, if q = p….
# define the variables
M <- 10 #the expected number of times her stake equals M before returning to 0
p <- .5 #p of winnning
q <- .5 #p of losing
n_simulations <- 10000 # simulations
# simulate game
simulate_game <- function(p, q, M) {
stake <- 0
reached_M <- 0
# loop (using while) until the stake reaches M or -M
while (stake < M && stake > -M) {
# Simulate a coin toss,
outcome <- sample(c(-1, 1), size = 1, prob = c(q, p))
# Update the stake based on the outcome of the coin toss, if stake is 0 then it goes to 1 for win, -1 for loss
if (outcome == 1) {
stake <- stake + 1
} else {
stake <- stake - 1
}
# Check if the stake equals M and increment the counter
if (stake == M) {
reached_M <- reached_M + 1
}
}
return(reached_M)
}
# Simulate games and calculate the average number of times the stake equals M before returning to 0
reached_M <- replicate(n_simulations, simulate_game(p, q, M))
average_num_reached_M <- mean(reached_M)
# Load the necessary libraries
library(ggplot2)
# Create a histogram to visualize the distribution of reached_M
ggplot(data.frame(reached_M = reached_M), aes(x = reached_M)) +
geom_histogram(binwidth = 1, color = "black") +
labs(title = "Distribution Stake Reaches M Before 0",
x = "Number of Times Reached M", y = "Frequency")