随机游走模拟中的总步数波动 - 需要帮助理解原因

问题描述 投票:0回答:1

我有一个有时有效的随机行走代码。 该算法仅使用基本 Python 在终端上打印矩阵;步行会增加它踩到的每个单元格,它就是这样做的。一个问题是有时它会比应有的步骤少(或多)一步。它应该在 step_count 等于 max_steps 时停止,但它只是偶尔.

这是我做的随机行走算法。我已经尝试从 while 循环的最大步数中删除负 1,但这只会使步数从 99–100 变为 100–101。我也尝试在 while 循环中添加另一个 if-then break,但是没有。

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 increaments 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)
python algorithm random random-walk
1个回答
0
投票

你的问题是起点,

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

应该改为

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

因为 randint 是包容性的,所以有些情况下你的第一步是在网格之外。

但是注意这样做会给你一个101的步数,因为你也在计算起点,你可以把步数减一,如果你不想数的话。

通过此更改,代码这一部分中的 if 语句已过时,

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

因为现在你的步行将产生始终在网格内的步骤, 所以你可以把它改成:

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

还有其他方法可以改进代码,但这是问题的根源。

© www.soinside.com 2019 - 2024. All rights reserved.