Python 随机生成的步行在绘制图表时给出相同的结果

Python randomly generated walks give same outcome when graphed

from pylab import *

no_steps = 10000

number = random()
position = zeros(no_steps)
position[0] = 0
time = zeros(no_steps)
time[0] = 0

for i in range(1, no_steps):
    time[i] = time[i-1] + 1
    if number >= 0.5:
        position[i] = position[i-1] + 1
        number = random()
    else:
        position[i] = position[i-1] - 1
        number = random()
plot(time, position)

number2 = random()
position2 = zeros(no_steps)
position2[0] = 0
time2 = zeros(no_steps)
time2[0] = 0
for t2 in range(1, no_steps):
    time2[t2] = time[t2-1] + 1
    if number2 >= 0.5:
        position2[t2] = position2[t2-1] + 1
        number2 = random()
    else:
        position2[t2] = position[t2-1] - 1
        number2 = random()
plot(time2,position2)

这应该通过每次生成一个随机数并检查条件来生成随机游走。因此,我假设如果它适用于一次步行,我可以添加更多相同的并在最后将它们全部放在同一个图表上。然而,显然这不是它的工作原理,最终绘制的图表非常相似,由于某种原因,位置差异为 -2 之一。如果我 运行 块与它们自己的程序分开,代码将生成两个完全不同的步行,只是当我将它们放在一起时它停止按预期工作。我到底错过了什么?

您不小心重复使用了第一个图中的变量:

for t2 in range(1, no_steps):
    time2[t2] = time[t2-1] + 1
    ^^^^^       ^^^^
    if number2 >= 0.5:
        position2[t2] = position2[t2-1] + 1
        number2 = random()
    else:
        position2[t2] = position[t2-1] - 1
        ^^^^^^^^^       ^^^^^^^^
        number2 = random()
plot(time2,position2)

我会用一个函数生成随机游走,所以你不必担心像这样重命名变量:

import numpy
from pylab import *

no_steps = 10000

def random_walk(no_steps):
    # 2 * [0, 1] - 1  ->  [0, 2] - 1  ->  [-1, 1]
    directions = 2 * numpy.random.randint(0, 2, size=(1, no_steps)) - 1
    positions = numpy.cumsum(directions)
    positions -= positions[0]  # To make it start from zero

    return positions

time1 = numpy.arange(0, no_steps)
plot(time1, random_walk(no_steps))
savefig('1.png')

clf()

time2 = numpy.arange(0, no_steps)
plot(time2, random_walk(no_steps))
savefig('2.png')