Write a program (including the random number generator) to plot the position as a function of time of a random walker in 1D that at each time step has an equal probability of making a step of ±1. Plot an ensemble of 10 trajectories, each 1000 points long, and overlay error bars of width 3σ(t) on the plot
import numpy as np
import matplotlib.pyplot as plt
# random number generator, using the example in (6.74)
def rng(Xn):
return ((8121 * Xn) + 28411) % 134456
num_lines = 10
num_points = 1000
half_prob = 134456 / 2.0
Xn = 0.5
for i in range(num_lines):
step = 0
walk = []
for i in range(num_points):
Xn = rng(Xn)
if Xn > half_prob:
step +=1
else:
step -=1
walk.append(step)
plt.plot(walk)
# Error bars for all iteration
# plt.errorbar(range(num_points), np.zeros(num_points), yerr=(3*np.sqrt(range(num_points))))
# Error bars for every 100
t = range(0, num_points, 100)
err = 3*np.sqrt(range(0, num_points, 100))
plt.errorbar(range(0, num_points, 100), np.zeros(num_points / 100), yerr=3*np.sqrt(range(0, num_points, 100)))
plt.ylabel("Steps")
plt.xlabel("Number of Iterations")
plt.show()
Generate bit sequence for maximal 4 LSFR
# initial - Xn-1, Xn-2, Xn-3, Xn-4
init_past = [1,1,1,1]
past = init_past
seq_list = []
while True:
Xn = (past[0] + past[3]) % 2
seq_list.append([Xn] + past)
past = [Xn] + past[0:3]
if past == init_past:
break
print seq_list
# random number generator, using the example in (6.74)
# constrained to 8 bits
def rng(Xn):
return ((8121 * Xn) + 28411) % 134456