Skip to content

Instantly share code, notes, and snippets.

@Kornel
Created September 11, 2016 17:11
Show Gist options
  • Save Kornel/341c28b15f67f8ebd73fd6dd1d706699 to your computer and use it in GitHub Desktop.
Save Kornel/341c28b15f67f8ebd73fd6dd1d706699 to your computer and use it in GitHub Desktop.
Random walk in R
library(ggplot2)
walk <- function(N, p = 0.5) {
cumsum((-1)^rbinom(N, 1, 1 - p))
}
# Convergence of the random walk
l <- sapply(1:1000, function(n){
N <- 100
tail(walk(N, 0.5), 1)
})
plot(density(l))
x <- seq(min(l), max(l), len = 100)
hx <- dnorm(x, mean(l), sd(l))
lines(x, hx, col = 'red')
# Display 3 random walks
N <- 1000
a <- walk(N, p = 0.5)
b <- walk(N, p = 0.45)
c <- walk(N, p = 0.40)
df <- data.frame(x = rep(1:N, 3), y = c(a, b, c), idx = rep(c('a', 'b', 'c'), each = N))
ggplot(df) +
geom_line(aes(x = x, y = y, colour = idx)) +
scale_color_brewer(palette = 'Dark2') +
theme_bw()
@Kornel
Copy link
Author

Kornel commented Sep 11, 2016

convergence

randomwalk

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment