【问题标题】:2D random walk, python2D 随机游走,python
【发布时间】:2019-09-15 01:52:14
【问题描述】:

我无法编写此代码。二维随机游走。二维随机游走模拟粒子在点网格中移动的行为。在每一步,随机游走者以 1/4 的概率向北、向南、向东或向西移动,与之前的移动无关。编写一个程序,该程序接受一个命令行参数 n 并估计随机游走者需要多长时间才能到达以起点为中心的 2n+1×2n+1 正方形的边界。

这是我写的所有代码。

    import sys
    import stdio
    import random

    # the size of the box, which should be 4
    n = int(sys.argv[1])

    # should be the amount of steps taken to reach the boundary/ end of the box.
    c = int(sys.argv[2])

    def random_walk_2D (n):
    x, y = 0, 0
    i = 4
   North = 1; South = 2; West = 3; East = 4

    for i in range(n):

    people = random.randint(1,4)

    while I < c:
    stdio.write(

    if people == 1:
    y = y + 1
    elif people == 2:
    y = y - 1
    elif people == 3:
    x = x + 1
    else :
    x = x - 1
    return (x, y)

    sdio.write('The walker took ')
    stdio.write(c)
    stdio.write(' steps. ')

我还需要添加一个 while 循环,但我不知道它的去向。我需要帮助。感谢您的回复

【问题讨论】:

  • 你的缩进有什么问题?
  • 我不明白你的问题
  • 如果您没有正确缩进代码,那么它将无法工作。
  • 最近的一个讨论在网格上快速实现stackoverflow.com/questions/69246926/…

标签: python arrays numpy python-requests 2d


【解决方案1】:
def random_walk_2d(n):
    xy = 0+0j
    cnt = 0
    while(np.abs(np.real(xy)) < n or np.abs(np.imag(xy)) < n):
        xy += np.random.choice([1j,-1j, 1, -1])
        cnt += 1

    return cnt

def simulate(N_sims,n):
    expected_move = 0
    for i in range(N_sims):
        expected_move += random_walk_2d(n)

    return expected_move/N_sims

【讨论】:

    猜你喜欢
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    相关资源
    最近更新 更多