For these two functions performing the same computation, why does the second take about eight times as long to run?
def random_walk_2(n):
"""Return coordinates after 'n' step random walk."""
x, y = 0, 0
for _ in range(n):
(dx, dy) = random.choice([(0, 1), (0, -1), (1, 0), (-1, 0)])
x += dx
y += dy
return (x, y) # 6.48 seconds for 20,000
def random_walk_3(n):
"""Return coordinates after 'n' step random walk."""
location = np.array([0, 0])
for _ in range(n):
move = np.array(random.choice([[0, 1], [0, -1], [1, 0], [-1, 0]]))
location += move
return location # 54.8 seconds for 20,000
TIA,
Mark