Search code examples
pythonrandommodulerandom-walk

Generating a 1D random walk with random module


I was trying to generate a random walk in 1D just with the random module. If a position at a certain moment is x, then the next position can be x+1 or x-1 with equal probability. I need to find the final position after 100 moves (start=0).

I have developed the following code, but I am not sure how I should should define the equal probability among the choices.

import random
def randomwalk1D(n):
    x = 0
    start = x
    xposition = [start]
    probabilities = [0.5, 0.5]
    for i in range(1, n + 1):
        step = random.choice(probabilities)
        if step > probabilities[0]:
            x += 1
        elif step < probabilities[1]:
            x -= 1
        xposition.append(start)
    return xposition

The function return just zeroes as result (putting n = 100). I only want to only use the random module. Could someone advise on what to do from here?


Solution

  • There are two issues with your code:

    1. You need to pass the choices of -1 and 1 to random.choice(), not the weights of those choices. You can also get rid of the direct comparisons with the elements from probabilities and the sampled step. If you want weighted sampling, use numpy.random.choice.
    2. You're adding start to the xpositions list repeatedly, even though you never update it. To resolve, append x instead, which represents the actual current position.

    Here is a code snippet that resolves both issues.

    import random
    def randomwalk1D(n):
        x = 0
        start = x
        xposition = [start]
        probabilities = [-1, 1]
        for i in range(1, n + 1):
            x += random.choice(probabilities)
            xposition.append(x)
        return xposition
    
    print(randomwalk1D(100))