【问题标题】:Python: Repetition of 2-d random walk simulationPython:重复二维随机游走模拟
【发布时间】:2014-10-16 02:21:01
【问题描述】:

我正在模拟二维随机游走,方向 0

a=np.zeros((1000,2), dtype=np.float)

def randwalk(x,y):
    theta=2*math.pi*rd.rand() # Theta is a random angle between 0 and 2pi
    x+=math.cos(theta);          # Since spatial unit = 1
    y+=math.sin(theta);          # Since spatial unit = 1
    return (x,y)

x, y = 0., 0.
for i in range(1000):
    x, y = randwalk(x,y)
    a[i,:] = x, y

这会生成一个单步走,并将所有中间坐标存储在 numpy 数组 a 中。如何编辑我的代码以重复步行 12 次(每次使用新的随机种子),然后将每次运行保存在单独的文本文件中?我的 randwalk 函数中是否需要一个 while 循环?

猜测:

rwalkrepeat = []

for _ in range(12):
    a=np.zeros((1000,2), dtype=np.float)
    x, y = 0., 0.
    for i in range(1000):
        x, y = randwalk(x,y)
        a[i,:] = x, y

rwalkrepeat.append(a)

print rwalkrepeat

【问题讨论】:

  • 重复上述 12 次,围绕你已有的内容的 for 循环会很好地工作。
  • 在发布问题之前,您应该尝试自己解决更多问题。你说,“我需要一个while循环吗..”,最好的答案是尝试让它与while循环一起工作。另外,尝试使用for 循环使其工作,因为您也知道这一点。另存为文本?,谷歌“numpy另存为文本”,看看你得到了什么..第一个命中是numpy.savetxt,第二个是numpy input and output
  • @tom10 我在帖子中添加了一个猜测。我在正确的路线上吗?

标签: python numpy random-walk


【解决方案1】:

您不需要任何显式循环。整个解决方案可以向量化(未经测试):

nsteps = 1000
nwalks = 12
theta = 2 * np.pi * np.random.rand(nwalks, nsteps - 1)
xy = np.dstack((np.cos(theta), np.sin(theta)))
a = np.hstack((np.zeros((nwalks, 1, 2)), np.cumsum(xy, axis=1)))

【讨论】:

    【解决方案2】:

    与您的代码的一般形式保持一致的方法是:

    import numpy as np
    import matplotlib.pyplot as plt
    import random as rd
    import math
    
    a=np.zeros((1000,2), dtype=np.float)
    
    def randwalk(x,y):
        theta=2*math.pi*rd.random() 
        x+=math.cos(theta);          
        y+=math.sin(theta);          
        return (x,y)
    
    fn_base = "my_random_walk_%i.txt"
    for j in range(12):
        rd.seed(j)
        x, y = 0., 0.
        for i in range(1000):
            x, y = randwalk(x,y)
            a[i,:] = x, y
        fn = fn_base % j
        np.savetxt(fn, a)
    

    对于基本计算,panda-34 和 NPE 的答案也不错,并利用了 numpy 的向量化。

    在这里,我使用seed(j) 将种子显式设置为随机数。这样做的好处是,只要种子相同,每个结果都是可重复的,即使它们没有按顺序运行,或者您更改了数组长度等。尽管如果没有'不想要可重复的运行——那么 random 将只是从时间中播种,并且所有运行中的所有随机数都会不同。

    文件名说明:由于 OP 要求将多个运行中的每一个保存到不同的文件,我认为有编号的文件会很好,例如,这里是 my_random_walk_0.txtmy_random_walk_1.txt 等。在我的示例中,我使用了名称fn_base 作为一个变量来保存文件名的一般格式,因此,比如说,代码fn = fn_base % 17 将设置fn 等于my_random_walk_17.txt(这对于python 来说有点老派,请阅读“字符串格式化”在python中了解更多)。

    【讨论】:

    • 谢谢,这很好用。您可能会说我对 Python 非常缺乏经验,fn 和 fn_base 是什么?
    • 我在答案末尾添加了解释。
    【解决方案3】:

    如果你使用 numpy,为什么不使用 numpy? 我会这样做:

    n_moves = 1000
    a = np.zeros((n_moves, 2))
    
    for i in range(12):
        thetas = (2*np.pi) * np.random.rand(n_moves-1)
        a[1:,0] = np.cos(thetas)
        a[1:,1] = np.sin(thetas)
        a = np.add.accumulate(a, 0)
    

    【讨论】:

      猜你喜欢
      • 2014-03-26
      • 1970-01-01
      • 2021-05-05
      • 2014-02-19
      • 1970-01-01
      • 2021-02-19
      • 2020-07-25
      • 1970-01-01
      相关资源
      最近更新 更多