我如何重复循环随机游走?

时间:2014-03-22 19:45:13

标签: python

我想计算1000次随机游走的平均值以获得良好的平均值,因此我的随机游走代码是

import math
import random
from matplotlib import pyplot
position = 0
walk = [position]
steps = 10
for i in xrange(steps):
    step = 1 if random.randint(0, 1) else -1
    position += step
    walk.append(position)

    print((walk))

pyplot.hist(walk)
pyplot.show()

所以,让python重复多次并计算这些随机游走的平均值的最佳方法是什么。 谢谢

1 个答案:

答案 0 :(得分:0)

如果将其细分为较小的函数,例如使代码的主要部分成为函数,将会更容易实现

def makewalk(steps):
  position = 0
  walk = [position]
  for i in xrange(steps):
    step = 1 if random.randint(0, 1) else -1
    position += step
    walk.append(position)
  return walk # instead of simply printing it

此外,您可以使用内置函数将其缩减为几行

import numpy
def makewalk(N):
  steps = numpy.random.randint(0, 2, N) * 2 - 1
  # an array of length N with random integers between 0 (inclusive) and 2 (exclusive)
  # multiplying it by two and subtracting 1 the numbers 0 and 1 become -1 and 1 respectively
  walk = numpy.cumsum(steps) # what it says, a cumulative sum
  return walk

现在只需循环1000次

from matplotlib import pyplot
steps = 10000
numwalks = 1000
walks = [makewalk(steps) for i in xrange(numwalks)]

有你的散步,随心所欲地做任何事情,并且由于散步是numpy数组,你可以很容易地计算没有循环的元素和

averagewalk = numpy.sum(walks, 0)*1.0/numwalks # sums along the 0th axis and returns an array of length steps