# Python code for 1-D random walk.
import random
import numpy as np
import matplotlib.pyplot as plt
# Probability to move up or down
prob = [0.05, 0.95]
n = 1000 # number of steps
# statically defining the starting position
start = 2
positions = [start]
# creating the random points
rr = np.random.random(n)
downp = rr < prob[0]
upp = rr > prob[1]
t = 1
step = (1/n)**0.5
for idownp, iupp in zip(downp, upp):
down = step if idownp and positions[-1] > 1 else 0
up = step if iupp and positions[-1] < 4 else 0
positions.append(positions[-1] - down + up)
# plotting down the graph of the random walk in 1D
x = [i*t/n for i in range(n+1)]
plt.plot(x, positions)
plt.xlabel('Time (seconds)')
plt.ylabel('Distance')
plt.title(f"Random Walk ({n} steps in {t} seconds)")
plt.grid(True)
plt.savefig("random_walk.png")
plt.show()
# Python code for 1-D random walk.
import random
import numpy as np
import matplotlib.pyplot as plt
# Probability to move up or down
prob = [0.05, 0.95]
n = 1000 # number of steps
# statically defining the starting position
start = 2
positions = [start]
# creating the random points
rr = np.random.random(n)
downp = rr < prob[0]
upp = rr > prob[1]
t = 1
step = (1/n)**0.5
for idownp, iupp in zip(downp, upp):
down = step if idownp and positions[-1] > 1 else 0
up = step if iupp and positions[-1] < 4 else 0
positions.append(positions[-1] - down + up)
# plotting down the graph of the random walk in 1D
x = [i*t/n for i in range(n+1)]
plt.plot(x, positions)
plt.xlabel('Time (seconds)')
plt.ylabel('Distance')
plt.title(f"Random Walk ({n} steps in {t} seconds)")
plt.grid(True)
plt.savefig("random_walk.png")
plt.show()