CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

| Download
Project: Teaching
Views: 195
Kernel: Python 3 (Anaconda 2022)

The Random Walk

The first cell loads two external modules

import random import matplotlib.pyplot as plt

Now we create a single random walk

x=[0] for j in range(10): n=random.randint(0,1) if n==1: x.append(x[j]+1) else: x.append(x[j]-1) plt.plot(x) plt.xlabel('n') plt.ylabel('displacement') plt.show()
Image in a Jupyter notebook

More walks on one page

for run in range(500): x=[0] for j in range(1000): n=random.randint(0,1) if n==1: x.append(x[j]+1) else: x.append(x[j]-1) plt.plot(x) plt.show()
Image in a Jupyter notebook

To investigate the average distance & displacement, we create a number of subloops. We end with two lists of the averages of many loops of different lengths

displacements=[] distances=[] for m in range(100): rundistances = [] rundisplacements = [] for run in range(1000): # do 1000 runs, each m steps long d=0 for j in range(m): n=random.randint(0,1) if n==1: d+=1 else: d-=1 rundisplacements.append(d) rundistances.append(abs(d)) displacements.append(sum(rundisplacements)/len(rundisplacements)) distances.append(sum(rundistances)/len(rundistances)) plt.plot(distances,'rx',label='distance') plt.plot(displacements,'bx',label='displacement') plt.legend() plt.show()
Image in a Jupyter notebook

The average displacement remains at zero, as expected. However, the average distance from the origin increases. This appears to be a square-root relationship.

import numpy as np distancesSqd = [i**2 for i in distances] x=np.arange(0,100) y=distancesSqd fit = np.polyfit(x,y,1) fit_fn = np.poly1d(fit) plt.plot(x,y, 'rx', x, fit_fn(x), '--k') plt.xlabel('n') plt.ylabel('distance squared') plt.show()
Image in a Jupyter notebook