Skip to content

Instantly share code, notes, and snippets.

@theopolisme
Created June 3, 2015 00:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save theopolisme/54004b2b5c5f72544364 to your computer and use it in GitHub Desktop.
Save theopolisme/54004b2b5c5f72544364 to your computer and use it in GitHub Desktop.
Random Walker
"""
randomwalker.py
(C) Theo Patt <theo@theopatt.com>
The RandomWalker emulates, surprise suprise, a random walk.
The random walker turns either left or right (50/50) and then
"walks" one unit in that direction.
Assignment: https://www.edmodo.com/post/434660789
"""
import math
import random
import itertools
import matplotlib.pyplot as plt
class RandomWalker(object):
def __init__(self):
self.heading = 0
self.start = [0, 0]
self.position = list(self.start)
self.history = [self.start]
def step(self):
turn = random.choice([1, -1])
if self.heading in [0, 2]:
self.position[0] += turn
else:
self.position[1] += turn
self.heading += turn
self.heading %= 4
self.history.append(list(self.position))
def distance(self):
return math.sqrt((self.position[0] - self.start[0]) ** 2 +
(self.position[1] - self.start[1]) ** 2)
def plot_history(self):
def pairwise(l):
a, b = itertools.tee(l)
next(b, None)
return itertools.izip(a, b)
def draw_arrow(A, B):
plt.arrow(A[0], A[1], B[0] - A[0], B[1] - A[1],
head_width=0.2, length_includes_head=True)
history = self.history
x = map(lambda v: v[0], history)
y = map(lambda v: v[1], history)
plt.scatter(x, y)
for a, b in pairwise(history):
draw_arrow(a, b)
plt.show()
def main():
for n_steps in xrange(0, 101):
distances = []
for i in xrange(50000):
walker = RandomWalker()
for i in xrange(n_steps):
walker.step()
# To view a graph of the walk, uncomment the following line
#walker.plot_history()
distances.append(walker.distance())
print n_steps, sum(distances)/len(distances)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment