如何分别绘制重复循环的结果?

时间:2018-12-18 12:07:07

标签: python for-loop matplotlib plot

我有一个1D随机游动的代码,我需要运行20次并将结果绘制在一张图中。该代码可正常运行1步,但我无法计算出如何进行多次步行。

我尝试了while循环和for循环,由于某种原因,它遍历了循环并 adds 结果,而不是回到开始并重新开始。因此,如果我有100步,并且想进行20遍,则绘制20 * 100 = 2000步的1步,而不是20步的100步。
这是我的代码:

import random
import matplotlib.pyplot as plt
import numpy as np

p=0.5
q=1-p
prob=[p,q]

N=100 #number of steps
n=20 #number of walks

start = 0  
positions = [start]
no_of_walks=list(range(0,n+1)) #since its a half open half closed interval

for n in no_of_walks:
    for i in range(0, N): 
        rr = random.random()
        right = rr < prob[0] and positions[-1] > -N
        left = rr > prob[1] and positions[-1] < N #length to be walked over 
        positions.append(positions[-1] - right + left)
        plt.plot(positions)

plt.show()

1 个答案:

答案 0 :(得分:1)

positions需要在每次走动之前重置,方法是将其移动到外循环中。

此外,我假设每次走动只应绘制一次,因此对plt.plot(...)的调用也应该进入外部循环(走动之后)。

import random
import matplotlib.pyplot as plt
import numpy as np

p=0.5
q=1-p
prob=[p,q]

N=100
n=20

start = 0  
#positions = [start]             # <- move this
no_of_walks=list(range(0,n+1))   #     |
                                 #     |
for n in no_of_walks:            #     v
    positions = [start]          # <- here
    for i in range(0, N): 
        rr = random.random()
        right = rr < prob[0] and positions[-1] > -N
        left = rr > prob[1] and positions[-1] < N
        positions.append(positions[-1] - right + left)
    plt.plot(positions)          # <- and move this out of the walk

plt.show()