-
8
Aug -
R Code for Brownian Motion
Posted by David Stockwell in All
According to Wikipedia the mathematical model for Brownian motion (also known as random walks) can also be used to describe many phenomena as well as the random movements of minute particles, such as stock market fluctuations and the evolution of physical characteristics in the fossil record. The simple form of the mathematical model for Brownian motion has the form:
St = eSt-1
where e is drawn from a probability distribution. My initial implementation of Brownian motion in R and 2 dimensions is this:

brownian< -function(n=1000,plot=T,fun=rnorm) {
x<-cumsum(fun(n))
y<-cumsum(fun(n))
plot(x,y,type="l")
}
brownian(fun=rnorm)
The code above makes use of the R feature of taking functions as parameters. In this case the Brownian motion is generated using the normal distribution rnorm. Random numbers can be generated in R from the following built in functions:
runif, rpois, rmvnorm, rnbinom, rbinom, rbeta, rchisq, rexp, rgamma, rlogis, rstab, rt, rgeom, rhyper, rwilcox, rweibull.
However if I wanted to generate Brownian motion with another distribution such a ‘power tail’ I need to change the function to handle the parameters. For example, the t distribution with df = n degrees of freedom has the following code and plot:

brownian< -function(n=1000,plot=T,fun=rnorm,df=1) {
x<-cumsum(fun(n,df))
y<-cumsum(fun(n,df))
plot(x,y,type="l")
}
brownian(fun=rt)
The limitations are clearly seen on the plot, as the 'longtail flights' tend to be in an x or y direction. Anyone like to generalize this code to properly handle any distribution in 2 dimensions?
- Published by David Stockwell in: All
- If you like this blog please take a second from your precious time and subscribe to my rss feed!