gpt4 book ai didi

python - 在Python中计算二维随机游走的均方位移

转载 作者:行者123 更新时间:2023-12-01 05:00:02 25 4
gpt4 key购买 nike

我正在模拟二维随机游走,方向 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?

最佳答案

这是计算均方位移 (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中计算二维随机游走的均方位移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26472653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com