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 0x7f50b0340cd0>]
_images/a7fdee397b6265ec804e34ebfdb6e116c7d22fdf600bebe6914076228ac26a40.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 0x7f50b03fa490>]
_images/c44b6e93339e6cbf7cac98fe6507335746499a7d5acf2b88fc9d190e49955687.png