In [9]:
# random integers
randint(0,1) # includes both 0 and 1
Out[9]:
1
In [30]:
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
        
In [12]:
rand_walk(1,10)
Out[12]:
[0, 1, 2, 3, 2, 3, 2, 1, 0, -1, 0]
In [19]:
sample_walk = rand_walk(1,10)
In [26]:
sample_walk
Out[26]:
[0, -1, 0, -1, -2, -1, 0, -1, 0, 1, 2]
In [25]:
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
Out[25]:
In [32]:
list_plot(rand_walk(0.1,10), plotjoined=true, thickness=0.5)
Out[32]:
In [45]:
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)
In [49]:
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
In [71]:
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
Out[71]:
In [ ]:
# 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)
In [80]:
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)
Out[80]: