! Random walk in 2 dimensions ! Program to accompany "Computational Physics" by N. Giordano and H. Nakanishi ! Copyright Prentice Hall 1997, 2006 program walk_2d option nolet library "sgfunc.trc" library "sglib.trc" randomize dim x2ave(1000) ! keep r^2 averages here call initialize(x2ave,n_walks,n_steps) ymax = sqr(n_steps) open #1: screen 0,1,0,0.93 set window -2*ymax,2*ymax,-2*ymax,2*ymax set background color "white" clear set color "black" plot area: -0.1,-0.1;-0.1,0.1;0.1,0.1;0.1,-0.1;-0.1,-0.1 plot 0,0; call calculate(x2ave,n_walks,n_steps) call display(x2ave) close #1 end ! initialize variables ! n_walks = number of walkers n_steps = number of steps taken by each walker sub initialize(x2ave(),n_walks,n_steps) input prompt "number of steps per walk => ": n_steps input prompt "number of walks => ": n_walks print "Hit p to pause, anything else to stop plotting." mat redim x2ave(n_steps) end sub ! do the calculation here ! x2ave(n) contains the average of r^2 at step n ! n_walks = total number of walkers ! n_steps = number of steps taken by each walker sub calculate(x2ave(),n_walks,n_steps) randomize cross_flag = 1 plot_flag = 1 for i = 1 to n_walks x = 0 ! current location of the walker y = 0 for j = 1 to n_steps r = rnd if r <= 0.25 then x = x + 1 else if r <= 0.5 then x = x - 1 else if r <= 0.75 then y = y + 1 else y = y - 1 end if if plot_flag = 1 and j") call datagraph(t,x2ave,1,0,"black") call addlsgraph(t,x2ave,1,"red") ! compute and plot least squares fit call fitline(t,x2ave,m,b) set cursor 4,20 print "slope = ";m;", steps =";n get key z end sub