这是仅使用 numpy 数组的随机游走问题的一个版本。为了找到位置被重新访问超过 500 步的时间,我们必须将位置的排序数组与其偏移量进行比较,记录它接近 0 的时间,然后增加偏移量。
到目前为止,这是我的代码,问题出在“while”循环中,我试图将位置重新访问为“zeroArray”中的元素的最终次数
当我运行它时,我得到一个索引错误,没有记录任何结果,并且即使循环停止的布尔表达式已经改变,计数器也已经迭代了很多次。
编辑:如何使用 numpy 数组查找重复位置:1)将最终位置数组排序为升序。2)比较具有增加偏移量的切片,只要您在该偏移量处找到 0.001m 内的位置,即您将位置与相邻位置(偏移量 1)进行比较。您可能会发现 18 个案例,其中邻居计算出在两个空间中您可能只会找到 2 个案例。在三个空格处,您会发现 0 停止。
import numpy as np
import random
MAX_STEP_SIZE = 0.90 # maximum size of a single step [m]
NUM_STEPS = 500 # number of steps in a random walk []
NUM_WALKS = 10 # number of random walks in a run []
TOLERANCE = 0.001 # separation of points considered the same [m]
STEP_TO_RECORD_1 = 100 # first step to record and analyze []
STEP_TO_RECORD_2 = 500 # 2nd step to record and analyze []
random.seed(12345)
#......................................................................distance
def distance(posA, posB) :
"""Distance between two positions"""
return np.abs(posA - posB)
#...............................................................initialPosition
def initialPosition() :
"""Initial position of walker at the start of a random walk"""
return 0.0
def genPositions(nSteps, maxStep) :
"""Return the new position after a random step between -maxStep and
maxStep, given the previous position"""
genArray1 = (maxStep - (-maxStep))*(np.random.random(nSteps+1)) + (-maxStep)
genArray1[0]=initialPosition()
return np.cumsum(genArray1)
oneStep = np.zeros(NUM_WALKS)
fiveStep = np.zeros(NUM_WALKS)
zeroStep = np.zeros(NUM_WALKS)
walkArray = np.zeros(NUM_WALKS)
counter = 1
hitcounter = 0
zerocounter = 0
keepchecking = bool(1)
for ii in range(NUM_WALKS):
position = (genPositions(NUM_STEPS, MAX_STEP_SIZE))
oneStep[ii] = position[100]
fiveStep[ii] = position[-1]
zeroArray = np.sort(position)
while keepchecking == bool(1):
zerocounter = 0
for jj in range(len(zeroArray)):
hitcounter = 0
if distance(zeroArray[jj+counter], zeroArray[jj]) <= TOLERANCE:
hitcounter +=1
zerocounter += hitcounter
counter +=1
if hitcounter == 0:
keepchecking = bool(0)
zeroStep[ii] = zerocounter
谢谢你的帮助,