This here is a version of the random walk problem using only numpy arrays. To find the times the position is revisited over 500 steps we have to compare a sorted array of the positions with its offset, record the time it is near 0 and then increase the offset.
Here's my code so far, the problem is in the 'while' loop where I'm trying to store the final amount of times the position is revisited as elements in the 'zeroArray'
When I run it I get an index error, no results recorded and a counter which has iterated many times too many even though the Boolean expression for the loop to stop has changed.
edit: How to find the repeated position with numpy array: 1) sort the final position array into increasing order. 2) Compare slices with increasing offsets as long as you find positions within 0.001m at that offset that is you compare positions to the neighbouring postions(offset 1). you might find 18 cases where the neighbours math that at two spaces you might find only 2 cases. And at three spaces you will find 0 at which point you stop.
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
Thanks for any help,