所以我正在模拟一维随机游走,有 1000 次游走,每次走 1000 步。
如何计算步行者返回原点的平均次数,然后计算步行者返回原点次数的标准差?
我觉得我不理解如何操纵它以获得我需要的答案的逻辑,所以如果有人可以提供帮助,那将非常有帮助!我现在的代码是:
def StepsFunc() :
step = np.random.randint( 2 )
#step is 0 or 1, want -1 or +1
if step == 0 :
step = -1
return step
#defining another function, which will actually take N number of steps
def Move( N ) :
x = 0 # starting from origin position
i = 0 # count
while i <= N-1 :
step = StepsFunc()
x += step
i += 1
return x
#number of steps
N = 1000
#number of random walks
walks = 1000
StepsList=[]
num=0
for i in range(walks):
x = Move( N )
if x == 0:
num += 1
StepsList.append( x )
print("The random walk returns to zero {} times".format(num))
print(np.mean(StepsList)) #average of all walks
print(num/walks) #getting the average number of walks that returned to zero?
#plt.hist(StepsList, bins='auto')
################################################# ###################
更新代码:
################################################# ###################
def Move( N ) :
x = 0 # starting from origin position
i = 0 # count
steps = [] # history of all positions after each step
for i in range(N) :
step = StepsFunc()
x += step
steps.append(x)
return steps
N = 1000
walks = 1000
StepsList=[]
for i in range(walks):
StepsList.append(Move( N ))
ZerosList = []
for x in StepsList:
temp = 0
for y in x:
if y == 0:
temp += 1
ZerosList.append(temp)
我可以使用它来计算平均值和标准差。