plot a 2d self avoiding random walk in python

To plot a 2D self-avoiding random walk in python, we can use the following code:

main.py
import numpy as np
import matplotlib.pyplot as plt
 
# Function to generate a 2D self-avoiding random walk
def self_avoiding_RW(n):
    positions = np.zeros((n, 2))
    positions[0] = [0, 0]
 
    for i in range(1, n):
        dx, dy = 0, 0
        while dx == 0 and dy == 0:
            dx, dy = np.random.choice([-1, 1]), np.random.choice([-1, 1])
        new_pos = positions[i-1] + [dx, dy]
        while any((new_pos == p).all() for p in positions[:i]):
            dx, dy = 0, 0
            while dx == 0 and dy == 0:
                dx, dy = np.random.choice([-1, 1]), np.random.choice([-1, 1])
            new_pos = positions[i-1] + [dx, dy]
        positions[i] = new_pos
    return positions
 
# Plotting the walk
positions = self_avoiding_RW(100)
plt.plot(positions[:, 0], positions[:, 1], 'b')
plt.show()
816 chars
26 lines

In this code, we first define a function called self_avoiding_RW that generates a 2D self-avoiding random walk of n steps. The function uses a while loop to generate a new position that is not already occupied by a previously generated position.

We then call self_avoiding_RW to generate a self-avoiding random walk of 100 steps and save the positions to positions. Finally, we plot the walk using plt.plot.

gistlibby LogSnag