如何将随机游走变为自我避免随机游走

时间:2019-08-09 07:12:25

标签: python

有人可以帮助我将随机游走更改为自我规避的随机游走吗?我尝试这样做,但没有成功。下面是随机游走的代码。

这是我的工作代码。


def random_walk_3D(N):
    Nsteps = range(N)
    xp,yp,zp = [0],[0],[0]
    pos = [0,0,0]
    rand = np.random.uniform(0,1,N)
    for i in Nsteps:
        # depending on the random number go right
        # left, up or down
        if 0.00000 <= rand[i] < 1.0/6.0: pos[0] = pos[0]+1
        if 1.0/6.0 <= rand[i] < 2.0/6.0: pos[0] = pos[0]-1
        if 2.0/6.0 <= rand[i] < 3.0/6.0: pos[1] = pos[1]+1
        if 3.0/6.0 <= rand[i] < 4.0/6.0: pos[1] = pos[1]-1
        if 4.0/6.0 <= rand[i] < 5.0/6.0: pos[2] = pos[2]+1
        if 5.0/6.0 <= rand[i] < 6.0/6.0: pos[2] = pos[2]-1
        xp.append(pos[0])
        yp.append(pos[1])
        zp.append(pos[2])

    return xp,yp,zp

1 个答案:

答案 0 :(得分:0)

我相信这里的主要问题是,避免步行的自我并不总是能获得固定的分数。根据定义,任何点只能访问一次,因此,在每个步骤中,可行方向的数量会有所不同,并且在您当前的代码中,它是固定的。


您绝对应该以更友好的方式存储访问点的历史记录。我想说的是(x,y,z)形式的元组列表。这使您可以更轻松地检查是否已经考虑了要选择的方向。通常,在每个步骤中,您都应按照以下步骤操作:

  1. 确定步行者可以走哪条路。
  2. 以相等的概率随机选择方向。
  3. 保存历史位置,以免再次访问。

一个简单的代码,您可以在下面找到:

import random


def get_possible_directions(point):
    """Point is in form (x, y, z)"""
    directions = [
        (point[0]+1, point[1], point[2]),  # right
        (point[0]-1, point[1], point[2]),  # left
        (point[0], point[1]+1, point[2]),  # forward
        (point[0], point[1]-1, point[2]),  # backward
        (point[0], point[1], point[2]+1),  # up
        (point[0], point[1], point[2]-1)   # down
    ]
    return directions


def random_walk_3D(N):
    Nsteps = range(N)
    current_position = (0, 0, 0)
    visited_points = []
    for _ in Nsteps:
        visited_points.append(current_position)
        all_directions = get_possible_directions(current_position)
        not_visited_directions = [direction for direction in all_directions if direction not in visited_points]
        current_position = random.choice(not_visited_directions)

    xp, yp, zp = zip(*visited_points)
    return xp, yp, zp  # returns tuples. If you want lists, just do list(xp), ...


if __name__ == "__main__":
    x, y, z = random_walk_3D(10)
    print(x)
    print(y)
    print(z)

您可能想看看random documentation。至于功能this的最后一步可以为您提供帮助。