I was asked to write the code of 100 random walkers, each with 1000 steps. then plot the steps of the average of the 100 walkers. I was able to plot all the walkers in one plot, but couldn't find a way to plot the average. any help will be appreciated. thank you.
here is my code:
import numpy as np
import matplotlib.pyplot as plt
import random
# 1
N = 100
for j in range(N):
def randomwalk1D(n):
x, t = 0, 0
# Generate the time points [1, 2, 3, ... , n]
time = np.arange(n 1)
position = [x]
directions = [1, -1]
for i in range(n):
# Randomly select either 1 or -1
step = np.random.choice(directions)
# Move the object up or down
if step == 1:
x = 1
elif step == -1:
x -= 1
# Keep track of the positions
position.append(x)
return time, position
rw = randomwalk1D(1000)
plt.plot(rw[0], rw[1], 'r-', label="rw")
plt.show()
CodePudding user response:
Modify your code like this:
import numpy as np
import matplotlib.pyplot as plt
import random
# 1
N = 100
walkers = [] # HERE
for j in range(N):
def randomwalk1D(n):
x, t = 0, 0
# Generate the time points [1, 2, 3, ... , n]
time = np.arange(n 1)
position = [x]
directions = [1, -1]
for i in range(n):
# Randomly select either 1 or -1
step = np.random.choice(directions)
# Move the object up or down
if step == 1:
x = 1
elif step == -1:
x -= 1
# Keep track of the positions
position.append(x)
return time, position
rw = randomwalk1D(1000)
walkers.append(rw)
plt.plot(rw[0], rw[1], 'r-', label="rw")
walkers = np.array(walkers) # HERE
plt.plot(walkers[0][0], walkers[:, 1].mean(axis=0), 'b-', label="mean") # HERE
plt.show()
Update
How can I calculate the root mean square of this array?
# Remove the time dimension, extract the position
arr = walkers[:, 1]
# Compute the Root Mean Square
rms = np.sqrt(np.mean(arr**2, axis=1))