diff --git a/main.py b/main.py index 9aac7f0..337b926 100644 --- a/main.py +++ b/main.py @@ -4,37 +4,27 @@ # Python code for 2D random walk. # Source: https://www.geeksforgeeks.org/random-walk-implementation-python/ + +import matplotlib.pyplot as plt +from randomwalk import Walker + import numpy import matplotlib.pyplot as plt import random +from randomwalk import Walker # defining the number of steps n = 100000 -# creating two array for containing x and y coordinate -# of size equals to the number of size and filled up with 0's -x = numpy.zeros(n) -y = numpy.zeros(n) - -# filling the coordinates with random variables +walker1 = Walker(100, 100) +walker2 = Walker(200, 200) for i in range(1, n): - val = random.randint(1, 4) - if val == 1: - x[i] = x[i - 1] + 1 - y[i] = y[i - 1] - elif val == 2: - x[i] = x[i - 1] - 1 - y[i] = y[i - 1] - elif val == 3: - x[i] = x[i - 1] - y[i] = y[i - 1] + 1 - else: - x[i] = x[i - 1] - y[i] = y[i - 1] - 1 - + walker1.walk() + walker2.walk() # plotting the walk plt.title("Random Walk ($n = " + str(n) + "$ steps)") -plt.plot(x, y) +plt.plot(walker1.x_coords, walker1.y_coords) +plt.plot(walker2.x_coords, walker2.y_coords) plt.savefig("./rand_walk_{}.png".format(n)) -plt.show() \ No newline at end of file +plt.show() diff --git a/randomwalk.py b/randomwalk.py new file mode 100644 index 0000000..41d85bb --- /dev/null +++ b/randomwalk.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""__description__ +""" + +__author__ = "Christina Ludwig, GIScience Research Group, Heidelberg University" +__email__ = "christina.ludwig@uni-heidelberg.de" + +import random + + +class Walker: + + def __init__(self, init_x=500, init_y=500): + """ + Create walker object + """ + self.x_coords = [init_x] + self.y_coords = [init_y] + + def walk(self): + """ + Walker walks one step forward in random direction + :return: + """ + last_x = self.x_coords[-1] + last_y = self.y_coords[-1] + new_x, new_y = self.nextStep(last_x, last_y) + self.x_coords.append(new_x) + self.y_coords.append(new_y) + + def nextStep(self, last_x, last_y): + """ + Choose next position randomly + :return: + """ + val = random.randint(1, 4) + if val == 1: + new_x = last_x + 1 + new_y = last_y + elif val == 2: + new_x = last_x - 1 + new_y = last_y + elif val == 3: + new_x = last_x + new_y = last_y + 1 + else: + new_x = last_x + new_y = last_y - 1 + return new_x, new_y