Created
October 26, 2018 18:09
-
-
Save slowkow/d28d6ce4c3739b58d75c96311fec4d37 to your computer and use it in GitHub Desktop.
Simulate lots of independent coin flip games, or just one long game.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Inspired by Ole Peters: https://youtu.be/LGqOH3sYmQA | |
# Play the coin flip game for n rounds. | |
# Win 50% of your holdings if you get heads | |
# Lose 40% of your holdings if you get tails | |
# Keep flipping for n rounds | |
play <- function(n) 100 * cumprod(ifelse(runif(n) > 0.5, 1.5, 0.6)) | |
n_plays <- 1e4 | |
# Let's simulate lots of idependent games | |
plays <- lapply(seq(n_plays), function(i) { | |
play(100) | |
}) | |
# Here we plot the results of each game, looks noisy | |
plot(1, type="n", xlab="", ylab="", | |
xlim=c(0, 100), ylim=c(0, log10(max(sapply(plays, max)))) | |
) | |
for (i in seq(n_plays)) { | |
lines(log10(plays[[i]])) | |
} | |
# Put each game into a column | |
mat <- do.call(cbind, plays) | |
# Average over all the games | |
avg <- log10(rowMeans(mat)) | |
plot(avg, type="l", xlab="", ylab="") | |
plot(log10(play(1e4)), type="l", xlab="", ylab="") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment