# random integers
randint(0,1) # includes both 0 and 1
def rand_walk(size, num_steps):
"""Plot a random walk with steps of given (vertical) size.
And num_steps number of steps.
Returns list of vertical coordinates."""
pos_list = [0]
for n in range(num_steps):
rand = 2*randint(0,1) - 1 # generates 1,-1 each with
# prob 1/2
new_pos = pos_list[-1] + (size*rand) # new vertical position
# after taking step in rand direction
pos_list.append(new_pos)
return pos_list
rand_walk(1,10)
sample_walk = rand_walk(1,10)
sample_walk
list_plot(sample_walk, plotjoined=true, thickness=0.5)
# if list is individual numbers (rather than pairs),
# list_plot assumes x-coords start at 0 and increase by 1
list_plot(rand_walk(0.1,10), plotjoined=true, thickness=0.5)
plot = list_plot(rand_walk(1,500000), plotjoined=true, thickness=0.1)
plot.save("rand_walk500000.pdf") # save plot to pdf so can zoom in more easily
show(plot)
def rand_walk_improved(vert_size, horiz_size, num_steps):
"""Return a list giving random walk with vert step size
equal to vert_size, horizontal step size equal horiz_size
And number of steps equal to num_steps.
Returns list of (x,y) pairs."""
pos_list = [(0,0)]
for n in range(num_steps):
rand = 2*randint(0,1) - 1 # generates 1,-1 each with
# prob 1/2
new_vert_pos = pos_list[-1][1] + (vert_size*rand) # new vertical position
# after taking step in rand direction
new_horiz_pos = pos_list[-1][0] + horiz_size
pos_list.append((new_horiz_pos, new_vert_pos))
return pos_list
list_plot(rand_walk_improved(1,1/100000,100000), plotjoined=true)
# want horiz_size to be inverse of num_steps
# so that horiz position ends up at 1
# Experiment to see how far move in vertical direction
# with a given number of steps of size 1
# 100 -> 4, 0, -11
# 1000 -> -20, -7, 9
# 10000 -> -100, -40, 60
# pattern: after n steps, go up or down around sqrt(n)
n = 100000 # number of steps
# random walk rescaled so that vertical displacement stays
# bounded
list_plot(rand_walk_improved(1/sqrt(n),1/n,n), plotjoined=true)