简体   繁体   English

R 中的 Levy Walk 模拟

[英]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:我正在尝试生成一系列数字来模拟 R 中的 Levy Walk。目前我正在使用以下代码:

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:下图显示了这样的 Levy Walk:在此处输入图片说明

The following histogram confirms that the numbers generated (ie f) actually belong to a power law:以下直方图确认生成的数字(即 f)实际上属于幂律:

在此处输入图片说明

My question is as follows: The step lengths generated (ie f) are quite large.我的问题如下:生成的步长(即 f)非常大。 Haw can I modify the code so that the step lengths only fall within some bound [fmin, fmax]?我可以修改代码以使步长仅落在某个范围内 [fmin, fmax] 吗?

PS I have intentionally not vectorized the code. PS 我故意没有对代码进行矢量化。

Try using this:尝试使用这个:

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

Note that you need 0 < fmin < fmax .请注意,您需要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.为了精确起见,您在这里模拟的是 Lévy 飞行。 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).因为这是一个列维散步,你应该允许从一开始粒子“走”每次飞行结束(用for ,例如)。 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.如果您使用plot(x, y, type = "o")绘制结果模拟,您将看到使用您的代码的航班(无步行)内没有位置。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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