4

我正在模拟二维随机游走,方向 0 < θ < 2π 和 T=1000 步。我已经有了:

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
4

3 回答 3

3

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

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)))
于 2014-10-15T15:03:55.243 回答
0

如果你使用 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-10-15T14:49:37.983 回答
0

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

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)明确地将种子设置为随机数。这样做的好处是,只要种子相同,每个结果都是可重复的,即使它们没有按顺序运行,或者您更改了数组长度等。尽管如果没有'不想要可重复的运行 - 然后随机将只是从时间开始,并且所有运行中的所有随机数都会不同。

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

于 2014-10-15T17:50:32.673 回答