我正在模拟二维随机游走,方向为0

a=np.zeros((1000,2), dtype=np.float)
print a                                   # Prints array with zeros as entries

# Single random walk
def randwalk(x,y):              # Defines the randwalk function
    theta=2*math.pi*rd.rand()
    x+=math.cos(theta);
    y+=math.sin(theta);
    return (x,y)                # Function returns new (x,y) coordinates

x, y = 0., 0.                   # Starting point is the origin
for i in range(1000):           # Walk contains 1000 steps
    x, y = randwalk(x,y)
    a[i,:] = x, y               # Replaces entries of a with (x,y) coordinates

# Repeating random walk 12 times
fn_base = "random_walk_%i.txt"      # Saves each run to sequentially named .txt
for j in range(12):
    rd.seed()                       # Uses different random seed for every run
    x, y = 0., 0.
    for i in range(1000):
        x, y = randwalk(x,y)
        a[i,:] = x, y
    fn = fn_base % j                # Allocates fn to the numbered file
    np.savetxt(fn, a)               # Saves run data to appropriate text file


现在,我要计算所有12个步行路程的均方位移。为此,我最初的想法是将每个文本文件中的数据导入到一个numpy数组中,例如:

infile="random_walk_0.txt"
rw0dat=np.genfromtxt(infile)
print rw0dat


然后以某种方式操纵阵列以找到均方位移。

是否有更有效的方法来找到我拥有的MSD?

最佳答案

这是计算均方差(MSD)的快速摘要。
路径似乎是由时间上等距的点组成的
为了你的兰德沃克。您可以将其放置在12步for循环中,并为每个a [i ,:]计算它

#input path =[ [x1,y1], ... ,[xn,yn] ].

def compute_MSD(path):
   totalsize=len(path)
   msd=[]
   for i in range(totalsize-1):
       j=i+1
       msd.append(np.sum((path[0:-j]-path[j::])**2)/float(totalsize-j))

   msd=np.array(msd)
   return msd

关于python - 用Python计算2d随机游动的均方位移,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26472653/

10-09 08:37