import numpy as np import matplotlib.pyplot as plt # Random Walk def randomWalks(n=100, nsteps=10000): plt.figure(figsize=(16,10)) for i in range(n): steps = np.random.choice([-1, 1], nsteps) positions = np.cumsum(steps) plt.plot(positions) plt.show() randomWalks() # 2D Random Walk def randomWalks2D(nsteps=25000): x, y = np.zeros(nsteps), np.zeros(nsteps) for step in range(1, nsteps): val = random.randint(1, 4) if val == 1: x[step], y[step] = x[step - 1] + 5, y[step - 1] elif val == 2: x[step], y[step] = x[step - 1] - 5, y[step - 1] elif val == 3: x[step], y[step] = x[step - 1], y[step - 1] + 5 else: x[step], y[step] = x[step - 1], y[step - 1] - 5 plt.figure(figsize=(16,10)) plt.title("2D Random Walk ($n = " + str(nsteps) + "$ steps)") plt.plot(x, y) plt.show() def main(): randomWalks2D() if __name__ == '__main__': main()