I am trying to perform a two-dimensional random walk for a particle, but I am not getting the desired result. The plot produced is a linear plot, which obviously should not have been. Similar code for a one-dimensional gives the desired result. Can someone please suggest where am I making any mistakes? Thanks.

import numpy
import random
HEAD = 1
TAIL = 2

a = numpy.zeros((2, 50))
b = a.transpose()
ns = 50                        # no of steps

for step in range(ns):
    for _ in range(ns):
        coin = random.randint(1,2)
        if coin == HEAD:
            b[step,0]+=1  # one unit length to the right
        elif coin == TAIL:
            b[step,1]-=1   # one unit length to the left
  • $\begingroup$ What plot are you referring to? $\endgroup$ – nicoguaro Jun 9 at 16:35
  • 1
    $\begingroup$ Your code says "If it's HEAD, go on to the right, else is its TAIL, go one down." As a consequence, you only ever move to the right or down, but never to the left or up. This is not the logic you wanted to implement, I suspect. $\endgroup$ – Wolfgang Bangerth Jun 9 at 16:44
  • $\begingroup$ I still could not get you, sorry, what part of my code, do you want me to change? Thanks $\endgroup$ – Roshan Shrestha Jun 9 at 16:58

You are only moving in one direction for each axis.

coin_x = random.randint(1,2)

# Move on x axis
if coin_x == HEAD:
elif coin_x == TAIL:

# Move on y axis
coin_y = random.randint(1,2)
if coin_y == HEAD:
elif coin_y == TAIL:


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.