# R Code for Brownian Motion

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?

## 0 thoughts on “R Code for Brownian Motion”

1. Levi Waldron says:

brownian

2. Levi Waldron says:

brownian

3. sarathsankarv says:

i cannot access the object brownian in R how can i access it

4. Anonymous says:

i cannot access the object brownian in R how can i access it

• Anonymous says:

You need to copy the code into your script and run it.

• Igor says:

I think there is a white space. It shout be “brownian<-" and not "brownian< -"

5. davids99us says:

You need to copy the code into your script and run it.

6. Igor says:

I think there is a white space. It shout be “brownian<-” and not “brownian< -“

7. Igor says:

I think there is a white space. It shout be “brownian<-” and not “brownian< -“

8. I think you mean:

brownian = function(n=1000,T=plot,fun=rnorm) {
x<-cumsum(fun(n))
y<-cumsum(fun(n))
T(x,y,type="l")
}
brownian()

• Anonymous says:

yes better

9. Benjamin Tovar says:

Hello! your code was very useful for my own implementation of a brownian motion simulation in R, here’s mine <- http://tata-box-blog.blogspot.mx/2012/12/brownian-motion-simulation-in-r.html  and thank you for the code. Benjamin

11. Pingback: livecooking

12. Pingback: strona www

13. Pingback: kliknij

14. Pingback: witryna

15. Pingback: strona firmy

16. Pingback: strona firmy

17. Pingback: oferta