Learn4life
Learn4life

Reputation: 227

How to plot results of repeated loop separately?

I have code for a 1D random walk, that I need to run 20 times and plot the results in one graph. The code works correctly for 1 walk, but i cant work out how to do it for multiple walks.

I have tried a while loop and a for loop, and for some reason it iterates over the loop and adds the results rather than going back to the beginning and starting again. So, if I have 100 steps and want to do this walk 20 times it plots one walk of 20*100=2000 steps, rather than 20 walks of 100 steps.
Here is my code:

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()

Upvotes: 1

Views: 316

Answers (1)

MB-F
MB-F

Reputation: 23637

positions needs to be reset before each walk, by moving it into the outer loop.

Furthermore, I assume each walk should be plotted only once, so the call to plt.plot(...) should go into the outer loop too (after the walk).

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()

Upvotes: 1

Related Questions