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?