Skip to content

Commit 73cef48

Browse files
committedJan 21, 2025
New vectorized walk function
1 parent 9f5bd14 commit 73cef48

File tree

3 files changed

+78
-12
lines changed

3 files changed

+78
-12
lines changed
 

‎.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
/venv*
44
.jupyter_cache
55
jupyter_execute
6+
__pycache__
67

78
# pixi environments
89
.pixi
910
*.egg-info
11+
_ipython-input*-profile

‎content/example/walk.py

+48-12
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,56 @@
1+
"""A 1-D random walk.
2+
3+
See also:
4+
- https://lectures.scientific-python.org/intro/numpy/auto_examples/plot_randomwalk.html
5+
6+
"""
17
import numpy as np
28

9+
310
def step():
411
import random
5-
return 1. if random.random() > .5 else -1.
12+
return 1.0 if random.random() > 0.5 else -1.0
13+
14+
15+
def walk(n: int, dx: float = 1.0):
16+
"""The for-loop version.
17+
18+
Parameters
19+
----------
20+
n: int
21+
Number of time steps
22+
23+
dx: float
24+
Step size. Default step size is unity.
25+
26+
"""
27+
xs = np.zeros(n)
628

7-
def walk(n):
8-
x = np.zeros(n)
9-
dx = 1. / n
1029
for i in range(n - 1):
11-
x_new = x[i] + dx * step()
12-
if x_new > 5e-3:
13-
x[i + 1] = 0.
14-
else:
15-
x[i + 1] = x_new
16-
return x
30+
x_new = xs[i] + dx * step()
31+
xs[i + 1] = x_new
32+
33+
return xs
34+
35+
36+
def walk_vec(n: int, dx: float = 1.0):
37+
"""The vectorized version of :func:`walk` using numpy functions."""
38+
import random
39+
steps = np.array(random.sample([1, -1], k=n, counts=[10 * n, 10 * n]))
40+
41+
# steps = np.random.choice([1, -1], size=n)
42+
43+
dx_steps = dx * steps
44+
45+
# set initial condition to zero
46+
dx_steps[0] = 0
47+
# use cumulative sum to replicate time evolution of position x
48+
xs = np.cumsum(dx_steps)
49+
50+
return xs
51+
1752

1853
if __name__ == "__main__":
19-
n = 100000
20-
x = walk(n)
54+
n = 1_000_000
55+
_ = walk(n)
56+
_ = walk_vec(n)

‎content/example/walk_ensemble_plot.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import numpy as np
2+
import matplotlib.pyplot as plt
3+
# See walk.py for the implementation
4+
import walk
5+
6+
7+
n_stories = 1000
8+
t_max = 200
9+
positions = np.empty((n_stories, t_max))
10+
11+
for i_story in range(n_stories):
12+
positions[i_story, :] = walk.walk(t_max, 1)
13+
14+
# Determine the time evolution of the root-mean-square distance.
15+
sq_distance = positions**2
16+
# Root mean square distance
17+
rms_distance = np.sqrt(np.mean(sq_distance, axis=0))
18+
19+
t = np.arange(t_max)
20+
21+
fig, ax = plt.subplots()
22+
ax.plot(t, rms_distance, "g", label="ensemble RMS distance")
23+
ax.plot(t, np.sqrt(t), "k--", label=r"theoretical $\sqrt{\langle (\delta x)^2 \rangle}$")
24+
ax.set(xlabel="time", ylabel="x")
25+
ax.legend()
26+
27+
plt.tight_layout()
28+
plt.show()

0 commit comments

Comments
 (0)
Please sign in to comment.