Random Walk simulator seems slow, are there ways to optimize my code? I'm trying to write a short random walk simulator in which an agent has a 50% chance on each "round" to either move toward x or back to its initial position. If the agent is already at its initial position and has to move back, it stays there instead.

I'm getting a lot of variance in the results and running the function with a distance to x of 2000 steps is already taking a while.

I was thinking I'd run the simulator over 200 steps 100 times and take the average of that, but with 40200 steps when x is 200 steps away on average, it's taking almost 10 seconds to run 100 times, which seems extremely slow.

Are there things I could optimize in my code to make it faster? Also, if you see glaring problems with design, suboptimal memory usage, etc...please don't hesitate to comment on those as well, thank you.

PS: I use a random int function of [0,1] for my 50% probability.

import numpy as np
import random as rand

def randomWalk(x):

    position = 0
    steps = 0

    while (position != x):
        move = rand.randint(0,1)
        steps += 1

        if (move == 1):
            position += 1

        elif (move == 0) &amp; (position != 0):
            position -= 1           

    return steps


trials = [0] * 100

for i in range(100):
    trials[i] = randomWalk(200)

sum = 0.

for trial in trials:
    sum += trial

avg = 0.

avg = sum / len(trials)

print avg
trials = [0] * 100
for i in range(100):
    trials[i] = randomWalk(200)



You don't need to create a list of zeroes in order to create a list of random walks.  Just use a list comprehension:

trials = [randomWalk(200) for _ in xrange(100)] # In Python3, you should use range().



sum = 0.
for trial in trials:
    sum += trial
avg = 0.
avg = sum / len(trials)



You shouldn't use sum as a variable name because it conflicts with the built-in function.  You know what?  You can use that built-in function:

avg = sum(trials, 0.) / len(trials)



print avg



I'm assuming that you are using Python2 just because of that line (and because of the decimal points in your numbers).  If you put parentheses around avg, your program would run in both versions.  Since I used xrange() above which is not around in Python3, you can't now; but you could also use range() up there to make it bothways-compatible.  range() takes up more memory than xrange(), in Python2, but with only a hundred numbers, it shouldn't really make much difference anyway.