Skip to content

Instantly share code, notes, and snippets.

@leoluyi
Created November 26, 2015 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save leoluyi/b0d0dfd0e5e482971c40 to your computer and use it in GitHub Desktop.
Save leoluyi/b0d0dfd0e5e482971c40 to your computer and use it in GitHub Desktop.
martingale <- function(max_round = 1000, init_token = 100, bid = 1,
rouletee_prob = c(19/37, 18/37)) {
## max_round: number of bidding
## init_token: initial # of chip
## bid: bidding chip when winning
## rouletee_prob: c(win, lose)
if (sum(rouletee_prob) != 1) stop("sum of 'rouletee_prob' must be 1")
capital = init_token ## current # of chip
PL <- 0 # the profit vector of the game
i=1
while (capital >= bid && i <= max_round) { # the requirement of bidding on the table
rout = sample(0:1, size = 1, prob = rouletee_prob, replace = T) # rouletee simulation
if(rout == 1) {
PL[i] = bid ## win "bid" chips
bid = 1 # bidding 1 chip in the next game
} else {
PL[i] = -bid # lossing "bid" chips
bid=bid*2 # double bid
}
capital = capital + PL[i] ## the capital
i=i+1
}
init_token + cumsum(PL)
}
## Plot
plot(martingale(),
lwd=3,font=2,
type="l", col="red",
xlab="The # of Bidding",
ylab="Cumulative Chips",
main="Martingale")
abline(h=init_token,col="green",lwd=2)
## Simulation
survival_round <- integer(10000)
final_token <- integer(10000)
for (i in 1:10000) {
mar_result <- martingale(max_round = 80, init_token = 10)
survival_round[i] <- length(mar_result)
final_token[i] <- tail(mar_result, n=1)
}
hist(survival_round, breaks=100)
hist(final_token, breaks=100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment