简体   繁体   中英

Levy Walk simulation in 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:在此处输入图片说明

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

在此处输入图片说明

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

PS I have intentionally not vectorized the code.

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)))

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.

library(ggplot2)
library(gridExtra)

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

fmin= 1
fmax= n

for (i in 2:n){
   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)))
}
ggplot(data.frame(x=x, y=y), aes(x, y))+geom_point()+geom_path()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM