CS 131 Fall 1998
Lab 5: For Loops & Random Walks
In this lab, you will combine turtle graphics with for loops to
perform simulations. In particular, you will write code which
simulates a random walk by repeatedly taking steps in random directions. You will also write code to perform numerous experiments with random walks, inclusing the verification of a theoretical result concerning the expected final distance of such a walk.
Brownian Motion & Random Walks
In 1828, a biologist Robert Brown used a microscope to discover that small pollen grains in a drop of water seemed to quiver in perpetual motion. Brown showed that this motion was not biological but physical and the phenomenon became known as Brownian motion in his honor. In 1905, the 25-year old Albert Einstein wrote a brilliant paper that developed a theory of Brownian motion, explaining quantitatively how the perpetual motion was a natural consequence of many ongoing collisions of tiny invisible atoms with the pollen grain. This paper created much excitement since it provided, for the first time, an experimental way to prove the existence of atoms, which was a very controversial issue at the turn of the century. In 1926, a French experimental scientist, Jean Perrin, won the Nobel prize in Physics for verifying Einstein's predictions and for making the first quantitative measurements of Brownian motion.
One simplified model of Brownian motion involves a particle which takes successive steps of a fixed size but in randomly chosen directions. This approximates the effects of collisions of a big object with many small atoms. The path taken by such a particle is often referred to as a "random walk", with the common analogy being that of an inebriated person staggering in random directions. The following JavaScript function simulates a random walk by repeatedly turning the turtle in a random direction and then taking a step forward. The for loop is controlled by the parameter to the function, which represents the total number of steps to be taken.
function randomWalk(numSteps)
// Given : numSteps > 0
// Results: displays a random walk of numSteps steps
{
var step;
home();
for (step = 1; step <= numSteps; step++) {
right(randomInt(1,360));
forward(5);
}
}
EXERCISE 1:
Type the randomWalk function definition into the JavaScript interpreter and call it several times. Describe the result.
What is the purpose of the call to home in this function?
EXERCISE 2:
You may notice that the random walks displayed by the
randomWalk function always use 5 as the step size. This
means that each step moves the walker 5 pixels on the screen.
Depending on the length of the walk, it might be desirable to change
the step size. For example, a long walk might need a smaller step
size to avoid wandering off the screen, while a short walk might be
easier to interpret with a larger step size. Modify the
randomWalk function so that it has an additional parameter
representing the step size. For example, the call randomWalk(500,
2) should result in a random walk of 500 steps, with each step
having length 2.
Note: the parameter for the step size should come after the parameter for the number of steps.
Once you have tested your modified function using various step sizes, save its definition in a document named Lab5.
EXERCISE 3:
Another drawback of the randomWalk function is that it is sometimes difficult to determine where a walk ends. This is especially a problem if multiple walks are displayed on the screen at the same time, since the steps in the different walks tend to obscure each other. Modify your randomWalk function so that it displays the coordinates of the turtle at its final location on the screen when the walk is completed. For example, a random walk that terminated at coordinates (8,28) might look like the following:
Reminder: in Lesson 6, you wrote code for displaying the coordinates of the turtle on the graphics screen.
Once you have tested your modified function, save its definition in Lab5.
Expectations of Random Events
Since random walks are, by definition, random in nature, you might think that there is no way to predict the result of a random walk. Statistically speaking, this is not true. Think back to our example with dice. Even though the dice are random, there are more ways for a 7 to come up on a roll than a 2. Thus, while a 2 is possible, a 7 is more likely. In the long run, after repeated rolls of the dice, you would expect to see many more 7's than 2's.
This same sort of predictability holds for random walks. While it is possible for a walker to head off in one direction and continue in a straight line, this is very unlikely. More often, the path taken will loop back upon itself and the walker will not venture too far off from its starting point.
In fact, it has been proven that after N random steps, such a walker will on average end up at a distance of sqrt(N) from its starting place. For example, a person taking 100 random steps, each one foot in size, will end up only 10 feet on average from their starting position.
EXERCISE 4:
Perform numerous simulations by making repeated calls to your randomWalk function without erasing the screen in between. Describe any patterns you see in your walks. Do all walks terminate
at roughly the same distance? Do they vary by large distances?
etc.
EXERCISE 5:
Write a JavaScript code segment which could be used to experimentally
test the theoretical result described above. That is, after N steps
the walker will end up roughly sqrt(N) steps from its starting point.
(Of course, if the step size is not 1, then the distance will be
sqrt(N) * stepSize.) Your code should:
- prompt the user for the number of steps and the step size for the random walk.
- simulate the random walk by calling your randomWalk function.
- display the final distance of the turtle relative to its starting point (recall that you wrote a distance function in Lesson 8).
- display the expected distance, along with the percentage that the simulated distance is off from the expected.
For example, a random walk of 100 steps, each of size 5, might produce the following results.
Actual distance = 43.657759905886145
Expected distance = 50
Percentage off = 13 %
Execute your code 5 times for each of the following values, and list your results.
- 100 steps, each of size 5
- 250 steps, each of size 5
- 500 steps, each of size 5
As the number of steps in the walk increases, does the accuracy of the final distance (relative to the expected value) increase or decrease? Are the results more consistent? Can you explain why?
Save your modified code in the document Lab5.
EXERCISE 6:
As you probably noted in the previous exercise, random walks can
produce very different results. It is only in the long run, after
many simulations, that you can expect to approach the theoretical value.
Manually re-executing your random walk code a large number
of times can become tedious. Instead, modify your code so that it
performs repeated simulations and averages the results. Your code
should:
- prompt the user for the number of walks, the number of steps in each walk, and the step size.
- simulate the specified number of random walks by repeatedly calling your randomWalk function.
- keep a running sum of the final distances, and display the average distance over all of the walks.
- display the expected distance, along with the percentage that the simulated average distance is off from the expected.
For example, a series of 10 random walks, each consisting of 100 steps of size 1, might produce the following results.
Average distance = 9.450955151339771
Expected distance = 10
Percentage off = 5 %
Execute your code for each of the following values, and list your results.
- 10 walks of 100 steps, each of size 5
- 50 walks of 100 steps, each of size 5
- 10 walks of 500 steps, each of size 1
Does increasing the number of random walks tend to increase or decrease the accuracy of your results (relative to the expected value)? Does increasing the number of steps in a walk tend to increase or decrease accuracy? Can you explain why?
Save your modified code in the document Lab5.
Extra Credit
With each step, a random walk randomly chooses one of 360 directions in which to take a step. Sometimes, a walk is more constrained. Imagine walking in a city such as Manhattan, where each block constitutes a step. Since most streets meet at right angles, you generally have four choices in directions (including turning around) at each corner. Define a variant of the randomWalk function called manhattanWalk which simulates such a walk, randomly choosing between four direction (at 90 degree intervals) between each step.
What would have to happen for a 10 step Manhattan walk to achieve the maximum possible distance? Is this more likely to occur for the Manhattan walk than for the 360-degree walk? Why or why not?
Hand in a printout of the Lab5 document, attached to these sheets.