我正在模拟二维随机游走,方向 0 < θ < 2π 和 T=1000 步。我已经有一个模拟单次步行的代码,重复 12 次,并将每次运行保存到按顺序命名的文本文件中:
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?