In [1]:
# import modules
import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline

# for pretty plots
import seaborn as sns
rc={'lines.linewidth': 2, 'axes.labelsize': 14, 'axes.titlesize': 14, \
    'xtick.labelsize' : 14, 'ytick.labelsize' : 14}
sns.set(rc=rc)
In [2]:
for i in range(10):
    print(np.random.uniform())
0.4953858152819727
0.17449007493520086
0.3265060267634693
0.2643879338086059
0.3449489933861839
0.6274639539222965
0.7638497535356991
0.029993334684860096
0.6206867052993685
0.6537509871790866

Greater than 0.5 means you move in the positive direction. Otherwise, you move in the negative direction.

In [3]:
# define number steps our particle should take
n_steps = 1000

# array to store positions
positions = np.zeros(n_steps)

for i in range(1, n_steps):
    
    # generate our random number (our coin flip)
    rand = np.random.uniform()
    
    # step in the positive direction
    if rand > 0.5:
        # put what should happen if rand > 0.5
        positions[i] = positions[i-1] + 1
        
    else:
        # put what should happen if rand > 0.5 is *not* met
        positions[i] = positions[i-1] - 1

plot our walker's position over time

In [4]:
plt.plot(positions)
Out[4]:
[<matplotlib.lines.Line2D at 0x1a1b89a748>]
In [5]:
# number of particles of to simulate
n_parts = 1000

# make 2D array to store our positions in
positions_2D = np.zeros([n_parts, n_steps])

# looping through the different walkers
for i in range(n_parts):
    
    # looping through the time steps
    for j in range(n_steps): 
        
        # generate random number
        rand = np.random.uniform()
        
        # step in the positive direction
        if rand > 0.5:
            positions_2D[i,j] = positions_2D[i,j-1] + 1
            
        # step in the negative direction
        else:
            positions_2D[i,j] = positions_2D[i,j-1] - 1

plot all the trajectories

In [6]:
# loop through trajectories to plot
for i in range(n_parts):
    plt.plot(positions_2D[i,:], color='k', alpha=0.01)
In [7]:
# make a histogram of final position
_ = plt.hist(positions_2D[:,-1], bins=20)
plt.xlim([-100,100])
Out[7]:
(-100, 100)
In [8]:
variances = np.zeros(n_steps)

for i in range(n_steps):
    var = np.var(positions_2D[:,i])
    variances[i] = var
In [9]:
plt.plot(variances)
plt.xlabel("steps")
plt.ylabel("variance")
Out[9]:
Text(0,0.5,'variance')