# Goal: draw random walk
# random numbers
randint(0,1) # generates "random" integer between 0 and 1, uniformly
# CHALLENGE: using just randint(0,1), (and basic arithmetic)
# create random variable that is -1,1, each with
# probability 1/2
2*randint(0,1) - 1
def basic_rand_walk(num_steps):
"""Produce random walk with num_steps steps.
Go up or down at each step, with probability 1/2 each."""
vert_list = [0] # list of vertical positions; vert_list[i] will be pos at time i
for n in range(num_steps):
# choose step size randomly
rand = 2*randint(0,1) - 1 # generates -1,1, each with prob 1/2
new_vert = vert_list[-1] + rand
vert_list.append(new_vert)
return vert_list
b = basic_rand_walk(10);
print(b)
list_plot(b, plotjoined=true)
list_plot(basic_rand_walk(100), plotjoined=true)
p5=list_plot(basic_rand_walk(100000), plotjoined=true, thickness=0.1);
show(p5)
p5.save("basic_rand_walk5.pdf")
p2=list_plot(basic_rand_walk(100), plotjoined=true, color='red')
p3=list_plot(basic_rand_walk(1000), plotjoined=true, color='green')
p4=list_plot(basic_rand_walk(10000), plotjoined=true, color='orange')
show(p2+p3+p4+p5)
# Goal: figure out appropriate rescaling so that basic_rand_walk(n) lives
# in a box of approximately fixed size (so then can take limit)
def rand_walk(num_steps, hor_step, vert_step):
"""Produce random walk with num_steps steps.
Horizontal step size = hor_step.
Vertical step size = vert_step.
Go up or down at each step, with probability 1/2 each."""
pos_list = [(0,0)] # list of (x,y) coords for pos
for n in range(num_steps):
# choose step size randomly
rand = 2*randint(0,1) - 1 # generates -1,1, each with prob 1/2
new_hor = pos_list[-1][0] + hor_step
new_vert = pos_list[-1][1] + rand*vert_step
pos_list.append((new_hor,new_vert))
return pos_list
r = rand_walk(10,3,5)
print(r)
list_plot(r, plotjoined=true)
list_plot(rand_walk(1000,3,5), plotjoined=true)
# How should we scale hor_step so that random walk always goes 1 total in hor direction?
n = 10000
list_plot(rand_walk(n, 1/n, 1), plotjoined=true)
# How should we scale vertical direction?
# Do experiment to figure out how far we move in vertical direction
# Number of steps: 100 -> 4, 10, 20
# 1000 -> 75, 50, 25
# 10000 -> 50, 150, 70
# vertical motion approx sqrt(num_steps)
n = 100
p2=list_plot(rand_walk(n, 1/n, 1/sqrt(n)), plotjoined=true)
show(p2)
n = 1000
p3=list_plot(rand_walk(n, 1/n, 1/sqrt(n)), plotjoined=true, color='red')
show(p3)
n = 10000
p4=list_plot(rand_walk(n, 1/n, 1/sqrt(n)), plotjoined=true, thickness=0.5, color='green')
show(p4)
show(p2+p3+p4)
# Correctly scaled, we can now compare random walks with different numbers of steps