Search code examples
pythonalgorithmrandomrandom-walk

Fluctuating total step count in random walk simulation - Need help understanding the cause


I have a random walking code that works sometimes.

The algorithm just uses base Python to print a matrix on the terminal; the walk increments every cell it steps on, and it does just that. The one problem is that sometimes it does one less step (or more) than it should. It should stop when the step_count is equal to max_steps, but it only does that occasionally.

Here is a random walking algorithm that I made. I've tried removing the minus 1 from the max steps on the while loop, but that just makes the step go from 99–100 to 100–101. I've also tried adding another if-then break inside the while loop, but nope.

import random

def walking(dimension):
    directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]  # cardinal directions: Up Down Right Left
    path=[]
    # randomizes the starting point. because that's more interesting
    start = (random.randint(0, dimension), random.randint(0, dimension))
    path.append(start)

    max_steps = 100 # can change to desired step amount
    step_count = 0
    while step_count < max_steps-1:
        x, y = path[-1]
        moves = []

        for dx, dy in directions:
            new_spot = (x + dx, y + dy)
            moves.append(new_spot)
      
        next_pos = random.choice(moves)
        if 0 <= next_pos[0] < dimension and 0 <= next_pos[1] < dimension:
            path.append(next_pos)
            step_count += 1


    return path

grid_size = 5 # can change to desired grid size
grid = [[0] * grid_size for _ in range(grid_size)]

walk = walking(grid_size)

for step in walk:
    x, y = step
    if 0 <= x < grid_size and 0 <= y < grid_size:
        grid[x][y] += 1 # this increments the cell its on

# calculates the summation of the entire matrix. 
total_sum = sum(sum(row) for row in grid)

# prints the updated grid and the summation which is equal the amount of steps
for row in grid:
    print('\t'.join(map(str, row)))

print("Steps taken:", total_sum)

Solution

  • Your issue is with the starting point,

    start = (random.randint(0, dimension), random.randint(0, dimension))
    

    should be changed to

    start = (random.randint(0, dimension-1), random.randint(0, dimension-1))
    

    because randint is inclusive, so there were cases where your first step was outside the grid.

    But note that doing this will give you a step count of 101, because you are also counting the starting point, you can just reduce the step count by one; if you don't want to count it. Disregard the note, it was only applicable when you had the <= in the while loop, that is when it was while step_count <= max_steps:

    With the change to start, the if statement in the following section of your code becomes obsolete,

    for step in walk:
        x, y = step
        if 0 <= x < grid_size and 0 <= y < grid_size:
            grid[x][y] += 1 # this increments the cell its on
    

    Because now your walk will produce steps that are always inside the grid, so you can change it to:

    for step in walk:
        x, y = step
        grid[x][y] += 1 # this increments the cell its on
    

    There are other ways in which you can improve your code, but this is the root of your issue.