Random walk (Python)

Contents

Random walk (Python)#

2D random walk#

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from numpy.random import default_rng
rng = default_rng()
# Parameters
N_PARTICLES = 100
N_STEPS = 10000
STEP_SIZE = 1
CHOICES = np.array([[0, 1], [1, 0], [0, -1], [-1, 0]])  # Up, right, down, and left
dx = CHOICES[rng.integers(4, size=(N_STEPS, N_PARTICLES))]
pos = dx.cumsum(axis=0) - dx[0, :, :]
fig, ax = plt.subplots(figsize=(10, 10))
ax.plot(pos[:, 0, 0], pos[:, 0, 1])
ax.plot(pos[:, 1, 0], pos[:, 1, 1])
[<matplotlib.lines.Line2D at 0x7f61d3673cb0>]
_images/8a67c73ec0d9e2e22ce38b62d2c171b4185d32c2e4d5f61818da6bd090f76791.png

Mean-squared displacement (MSD)

fig, ax = plt.subplots(figsize=(10, 10))
msd = np.mean(np.sum(pos**2, axis=1), axis=1)
ax.plot(np.arange(N_STEPS), msd)
[<matplotlib.lines.Line2D at 0x7f61d349cad0>]
_images/540b60e442a35718f97a5449463826f1f99b635da546e3581c6b8f93e2a58965.png