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

0 投票
1 回答
1427 浏览
提问于 2025-04-17 23:27

我想要进行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

如果把问题拆分成小的功能来做,会简单很多,比如把你代码的主要部分做成一个函数。

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

撰写回答