-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrandom_walk1.py
More file actions
76 lines (61 loc) · 1.86 KB
/
random_walk1.py
File metadata and controls
76 lines (61 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# -*- coding: utf-8 -*-
"""Random Walk1.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1ORkwEqoi33Qt9Bh0UGVNZhrxNBbkpSos
"""
#1D
import matplotlib.pyplot as plt
import random
def random_walk_1d(steps):
walk = [0] # start from position 0
for i in range(steps):
step = -1 if random.randint(0, 1) == 0 else 1 # either step -1 or 1
walk.append(walk[-1] + step) # add the step to the last position
return walk
steps = 1000 # for example, a walk of 1000 steps
walk = random_walk_1d(steps)
plt.figure(figsize=(10,6))
plt.plot(walk)
plt.title('1D Random Walk')
plt.xlabel('Steps')
plt.ylabel('Position')
plt.show()
def random_walk_2d(steps):
x, y = [0], [0] # start from position (0, 0)
for _ in range(steps):
dx = random.choice([-1, 0, 1])
dy = random.choice([-1, 0, 1])
x.append(x[-1] + dx)
y.append(y[-1] + dy)
return x, y
x, y = random_walk_2d(1000)
plt.figure(figsize=(10,6))
plt.plot(x, y)
plt.title('2D Random Walk')
plt.xlabel('X Position')
plt.ylabel('Y Position')
plt.axis('equal') # make the axes equal, so the walk appears unbiased
plt.show()
import matplotlib.pyplot as plt
import random
from mpl_toolkits.mplot3d import Axes3D
def random_walk_3d(steps):
x, y, z = [0], [0], [0] # start from position (0, 0, 0)
for _ in range(steps):
dx, dy, dz = random.choice(
[(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1), (0, 0, 0)]
)
x.append(x[-1] + dx)
y.append(y[-1] + dy)
z.append(z[-1] + dz)
return x, y, z
x, y, z = random_walk_3d(1000)
fig = plt.figure(figsize=(10,6))
ax = fig.add_subplot(111, projection='3d')
ax.plot(x, y, z)
ax.set_title('3D Random Walk')
ax.set_xlabel('X Position')
ax.set_ylabel('Y Position')
ax.set_zlabel('Z Position')
plt.show()