Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Levy Walk simulation in R

Tags:

r

I am trying to generate a series of numbers to simulate a Levy Walk in R. Currently I am using the following code:

alpha=2
n=1000
x=rep(0,n)
y=rep(0,n)

for (i in 2:n){
   theta=runif(1)*2*pi
   f=runif(1)^(-1/alpha)
   x[i]=x[i-1]+f*cos(theta)
   y[i]=y[i-1]+f*sin(theta)
}

The code is working as expected and I am able to generate the numbers according to my requirements. The figure below shows on such Levy Walk: enter image description here

The following histogram confirms that the numbers generated (i.e. f) actually belong to a power law:

enter image description here

My question is as follows: The step lengths generated (i.e. f) are quite large. Haw can I modify the code so that the step lengths only fall within some bound [fmin, fmax]?

P.S. I have intentionally not vectorized the code.

like image 824
DotPi Avatar asked Oct 06 '13 11:10

DotPi


2 Answers

Try using this:

f=runif(1, fmax^(-alpha), fmin^(-alpha))^(-1/alpha)

Note that you need 0 < fmin < fmax.

BTW, you can vectorize your code like this:

theta <- runif(n-1)*2*pi
f <- runif(n-1, fmax^(-alpha), fmin^(-alpha))^(-1/alpha)
x <- c(0, cumsum(f*cos(theta)))
y <- c(0, cumsum(f*sin(theta)))
like image 68
Ferdinand.kraft Avatar answered Oct 28 '22 13:10

Ferdinand.kraft


Just for precision, what you're simmulating here is a Lévy flight. For it to be a Lévy walk, you should allow the particle to "walk" from the beginning to the end of each flight (with a for, for example). If you plot your resulting simmulation with plot(x, y, type = "o") you will see that there are no positions within flights (no walking) using your code.

like image 27
Jordi F. Pagès Avatar answered Oct 28 '22 14:10

Jordi F. Pagès