Cara menggunakan python random walk 2d

Computer science is amazing! Even simple, rule based algorithms can demonstrate complex behavior and create beautiful things. Random Walk is one of these algorithms.

It’s used in financial markets simulations, physics, computer networking, psychology, and even gambling. Practically any aspect of the universe which contains some form of randomness can be simulated with help of random walk.

Check this great sculpture in London designed by random walk algorithm:

Image by Andy Roberts

That’s why it’s so important to know how to implement this algorithm. Next we will do it with python.

Implementation

I will write 2 main functions and 1 helper function. The first function will generate 2 dementia spaces and the second simulates a random walk on this space. The helper function will update the position of our walker in space.

To make the process more fun, I gave our walker such attributes as points and health. There are a lot of pizzas on the 2-d map. If the walker steps on the point where pizza is, they will gain 1 point and increase their health by 1 (but no more than 50). Also, if a walker hits the virtual wall (limits of the generated space) it will lose 1 health point. And let’s add the condition that if walkers’ health gets to 0 the game will be over. Fun, right? Let’s write some code.

Space generation:

Pass the size of the area. We will have space in the form of the square, area of the square equals square of its side. If you pass 100, you will have 1000 data points in generated space. The space I will store in the object of the tuples. Each tuple will have data about pizzas and if walker visited it. Also, let’s randomize the initial position of the walker.

Walk simulation:

Here the magic happens. A random generator will give us numbers in range 1–4 to determine the direction for the next move. On each move, we will check if we found pizza and if we hit the wall. Depending on the situation stats of the walker will be updated. Also every move of the walker will be recorded so we can visualize it later.

After running the simulation 100 times, this is how walker’s moves look like:

You can see how position changed on each step. But gazing at a raw array of tuples is not fun, let’s visualize the date.

Visualization

Here how simple visualization can be done:

First extracting x and y coordinates from the tuples and then feed them to the matplotlib. It will draw the plot something like this (but never the same because we working with random events):

But again, watching the static image gives us not much fun, let’s animate the process of walking.

This is how we do it:

First let’s declare empty arrays which will be filled in the future with steps of our walker. Second is the size of the plot. Each coordinate (x and y) should match the size of the space you have generated. Then write a function which will take a data point from the original array and add it to the line array. And finally pass all this to the FuncAnimation function.

And here our walker is alive:

Full code:

Conclusion

Learning algorithms and computational models is very important for the developers and researchers. Today we demonstrate how to use a random walk algorithm. Which appears to be not only applicable in a wide range of fields, but also super fun to play with.

In mathematics, random walk is the process in which objects randomly wander away from where they started.

Here is a video that shows how a particle collides with other particles in two dimensions. The path of the yellow particle is described by random walk:

Random walk is easy to visualize using Python. Here are illustrations of random walks in 1D, 2D, and 3D:

1D Random Walk2D Random Walk3D Random Walk

Today you learn how to plot these three graphs by implementing the random walk algorithm in Python.

Why Is Random Walk Useful

Randomness is always present in nature.

When you drop a droplet of the colorant into a glass of water it mixes up automatically without you stirring it.

But how and why does this happen?

Water molecules in the glass vibrate rapidly on a microscopic level. When the colorant molecules collide with the rapidly vibrating water molecules, they bump around in random directions. This eventually mixes the water and the colorant and makes it an evenly colored mix.

If you take one colorant molecule under inspection, you can see its path is completely random. This is because it collides with the water molecules that are vibrating in random directions. If you want to simulate a colorant molecule in a glass of water, you would do it with a random walk.

The random walk algorithm is useful as it can be used to simulate common phenomena of nature.

How to Implement Random Walk in Python

The random walk can be easily implemented in Python. A great starting point is to start with the 1D random walk.

To make the one-dimensional random walk work:

  1. Initialize an object at position y.
  2. Randomly move the object up or down. In other words, add or subtract 1 from the y value.
  3. Keep track of all the positions of the object, that is, the y values.

Then, to implement 2D and 3D random walks, expand this idea into 2 and 3 dimensions.

Disclaimer: This post contains affiliate links.

Prerequisites

The random walk algorithm itself can be implemented natively in Python. But you need to use a library to visualize the results plus some utilities for generating lists of numbers.

In this guide, you are going to use these two external packages:

  • NumPy for generating lists of numbers.
  • Matplotlib for plotting the results of each random walk.

To work with these packages, you need to have them installed on your machine. You can install these with Pip by running the following command in your command line window:

pip install numpy
pip instal matplotlib

Now you are all set. Let’s get started with the random walks.

1D Random Walk

The most basic random walk is the 1D random walk. In this form of random walk, the moving object is restricted to move in one dimension only. In our case, up and down.

The idea is that the object takes a step up or down randomly n times and stores the position values into a list.

Because the movement of the object is one-dimensional, the graph that illustrates the path is a line of some height. This is not useful, because it is impossible to tell where the object was at each step. To make the graph more informative, we are going to assign a timestamp for each step. This makes it a 2D graph with the object’s position as the y-axis and the timestamp on the x-axis.

Here is the function that implements the 1D random walk with n timepoints. Please, take a look at the comments in the code. Also, this is not the most elegant implementation but it is the easiest to understand:

import numpy as np
import matplotlib.pyplot as plt
import random

def randomwalk1D(n):
    x, y = 0, 0

    # Generate the time points [1, 2, 3, ... , n]
    timepoints = np.arange(n + 1)
    positions = [y]

    directions = ["UP", "DOWN"]
    for i in range(1, n + 1):

        # Randomly select either UP or DOWN
        step = random.choice(directions)
        
        # Move the object up or down
        if step == "UP":
            y += 1
        elif step == "DOWN":
            y -= 1

        # Keep track of the positions
        positions.append(y)

    return timepoints, positions

Now you can create a random walk and plot the timepoints as the x-axis and the position of the object as y-axis:

time_data, pos_data = randomwalk1D(1000)

plt.plot(time_data, pos_data, 'r-')
plt.title("1D Random Walk in Python")
plt.show()

Output:

The object moves up or down randomly in a 1D random walk.

To make a comparison, you can plot multiple results of 1D random walks into the same graph:

rw1 = randomwalk1D(1000)
rw2 = randomwalk1D(1000)
rw3 = randomwalk1D(1000)

plt.plot(rw1[0], rw1[1], 'r-', label="rw1")
plt.plot(rw2[0], rw2[1], 'g-', label="rw2")
plt.plot(rw3[0], rw3[1], 'b-', label="rw3")

plt.show()

Output:

Multiple 1D random walks produce different graphs because each walk is random.

Full Code

import numpy as np
import matplotlib.pyplot as plt
import random

def randomwalk1D(n):
    x, y = 0, 0

    # Generate the time points [1, 2, 3, ... , n]
    timepoints = np.arange(n + 1)
    positions = [y]

    directions = ["UP", "DOWN"]
    for i in range(1, n + 1):

        # Randomly select either UP or DOWN
        step = random.choice(directions)
        
        # Move the object up or down
        if step == "UP":
            y += 1
        elif step == "DOWN":
            y -= 1

        # Keep track of the positions
        positions.append(y)

    return timepoints, positions

rw1 = randomwalk1D(1000)
rw2 = randomwalk1D(1000)
rw3 = randomwalk1D(1000)

plt.plot(rw1[0], rw1[1], 'r-', label="rw1")
plt.plot(rw2[0], rw2[1], 'g-', label="rw2")
plt.plot(rw3[0], rw3[1], 'b-', label="rw3")

plt.show()

Now that you know how to implement the random walk algorithm in 1 dimension, let’s move on to higher dimensions.

2D Random Walk

The idea behind the random walk in 2D is the exact same as in one dimension. Now the movement of the object is no longer restricted to up/down. Instead, it can move to the left or right too.

In the 2D case, you are not plotting against time anymore. Instead, it is possible to visualize the walk by plotting the x, y coordinate pairs into the graph. This draws the 2D path the object took with n steps.

Here is how the algorithm looks in code:

import numpy as np
import matplotlib.pyplot as plt
import random

def randomwalk2D(n):
    # [0, 0, 0, ... ,0]
    x = np.zeros(n)
    y = np.zeros(n)

    directions = ["UP", "DOWN", "LEFT", "RIGHT"]
    for i in range(1, n):
        # Pick a direction at random
        step = random.choice(directions)
        
        # Move the object according to the direction
        if step == "RIGHT":
            x[i] = x[i - 1] + 1
            y[i] = y[i - 1]
        elif step == "LEFT":
            x[i] = x[i - 1] - 1
            y[i] = y[i - 1]
        elif step == "UP":
            x[i] = x[i - 1]
            y[i] = y[i - 1] + 1
        elif step == "DOWN":
            x[i] = x[i - 1]
            y[i] = y[i - 1] - 1
    
    # Return all the x and y positions of the object
    return x, y

Here is an example run of a 2D random walk with 1000 steps.

x_data, y_data = randomwalk2D(1000)

plt.title("2D Random Walk in Python")
plt.plot(x_data, y_data)
plt.show()

Here is a path that the above code produces:

2D Random walk with 1000 steps.

Full Code

import numpy as np
import matplotlib.pyplot as plt
import random

def randomwalk2D(n):
    # [0, 0, 0, ... ,0]
    x = np.zeros(n)
    y = np.zeros(n)

    directions = ["UP", "DOWN", "LEFT", "RIGHT"]
    for i in range(1, n):
        # Pick a direction at random
        step = random.choice(directions)
        
        # Move the object according to the direction
        if step == "RIGHT":
            x[i] = x[i - 1] + 1
            y[i] = y[i - 1]
        elif step == "LEFT":
            x[i] = x[i - 1] - 1
            y[i] = y[i - 1]
        elif step == "UP":
            x[i] = x[i - 1]
            y[i] = y[i - 1] + 1
        elif step == "DOWN":
            x[i] = x[i - 1]
            y[i] = y[i - 1] - 1
    
    # Return all the x and y positions of the object
    return x, y

x_data, y_data = randomwalk2D(1000)

plt.title("2D Random Walk in Python")
plt.plot(x_data, y_data)
plt.show()

3D Random Walk

Now that you have the 1D and 2D random walks working, let’s finally implement the 3D one.

The idea is exactly the same as in 2D, but now you can move up/down, left/right, and also inward/outward.

Here is how the algorithm looks in code:

import matplotlib.pyplot as plt
import numpy as np
import random

def randomwalk3D(n):
    x, y, z = np.zeros(n), np.zeros(n), np.zeros(n)

    directions = ["UP", "DOWN", "LEFT", "RIGHT", "IN", "OUT"]
    for i in range(1, n):
        step = random.choice(directions)

        if step == "RIGHT":
            x[i] = x[i - 1] + 1
            y[i] = y[i - 1]
            z[i] = z[i - 1]
        elif step == "LEFT":
            x[i] = x[i - 1] - 1
            y[i] = y[i - 1]
            z[i] = z[i - 1]
        elif step == "UP":
            x[i] = x[i - 1]
            y[i] = y[i - 1] + 1
            z[i] = z[i - 1]
        elif step == "DOWN":
            x[i] = x[i - 1]
            y[i] = y[i - 1] - 1
            z[i] = z[i - 1]
        elif step == "IN":
            x[i] = x[i - 1]
            y[i] = y[i - 1]
            z[i] = z[i - 1] - 1
        elif step == "OUT":
            x[i] = x[i - 1]
            y[i] = y[i - 1]
            z[i] = z[i - 1] + 1

    return x, y, z

And here is an example of a 3D random walk with 1000 steps plotted in a 3D interactive graph:

x_data, y_data, z_data = randomwalk3D(1000)

ax = plt.subplot(1, 1, 1, projection='3d')
ax.plot(x_data, y_data, z_data, alpha=0.9)
ax.scatter(x_data[-1], y_data[-1], z_data[-1])

plt.show()

Output:

A 3D random walk in Python with 1000 steps.

If you run this code on your machine, you can freely rotate the resulting graph to inspect it in other directions.

Full Code

import numpy as np
import matplotlib.pyplot as plt
import random

def randomwalk1D(n):
    x, y = 0, 0

    # Generate the time points [1, 2, 3, ... , n]
    timepoints = np.arange(n + 1)
    positions = [y]

    directions = ["UP", "DOWN"]
    for i in range(1, n + 1):

        # Randomly select either UP or DOWN
        step = random.choice(directions)
        
        # Move the object up or down
        if step == "UP":
            y += 1
        elif step == "DOWN":
            y -= 1

        # Keep track of the positions
        positions.append(y)

    return timepoints, positions
0

Become a Pro Data Visualizer in Python

If you are interested in learning more data visualization in Python, I highly suggest you enroll in Udemy’s Python Data Visualization Course.

Source: Udemy.com

Conclusion

Today you learned how to implement random walk in Python in 1D, 2D, and 3D.

To recap, a random walk is a process where an object starts wandering by taking steps in random directions. This process is present in nature in many ways.

To implement a random walk algorithm in Python, initialize an object at a starting point and start moving it around in random directions n times.