-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandom_walk.py
More file actions
50 lines (40 loc) · 1.05 KB
/
random_walk.py
File metadata and controls
50 lines (40 loc) · 1.05 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
import random
"""def random_walk(n):
x = 0
y = 0
for i in range(n):
step = random.choice(['N', 'S', 'E', 'W'])
if step == 'N':
y += 1
elif step == 'S':
y -= 1
elif step == 'E':
x += 1
else:
x -= 1
return (x, y)
for i in range(25):
walk = random_walk(10)
print(walk, "Distance from home = ", abs(walk[0]) + abs(walk[0]))"""
def random_walk_2(n):
x, y = 0, 0
for i in range(n):
(dx, dy) = random.choice([(0, 1), (0, -1), (1, 0), (-1, 0)])
x += dx
y += dy
return (x, y)
number_of_walks = 15000
for walk_length in range(1, 31):
no_transport = 0
for i in range(number_of_walks):
(x, y) = random_walk_2(walk_length)
distance = abs(x) + abs(y)
if distance <= 4:
no_transport += 1
no_transport_percentage = float(no_transport) / number_of_walks
print(
"Walk size = ",
walk_length,
" / % of no trnasport = ",
100 * no_transport_percentage,
)