EZ Math Movie, Tutorials, Turtle Graphics, Random Walk

The random walk

We will make the turtle walk around randomly. It will move a bit during each cycle of the loop code.  Each time that the turtle moves it will be over a random distance and in a random direction. This motion is sometimes called a random walk.

Move a random distance.

In every cycle of the loop code we will make a random real number between 0 and 1. This will be the distance that the turtle will move. We will use the command randomRealRange to get this distance, and we will place this value into a variable named distance. The code used to get this distance looks like this:

distance = randomRealRange(0, 1);

Later in the loop code we will move the turtle forward through this distance with code that looks like this:


Move in a random direction.

Also, in every loop cycle we will make a random real number between 0 and 360. This number will be the turning angle for the turtle. After each move forward the turtle will turn right this number of degrees. This will randomly aim the turtle for the next forward move. Note that even though it always turns right, the final aim of the turtle can be any direction on the (x, y) plane, since the range of random angles covers all those around a circle. We will get this turning angle using randomRealRange and place it into a variable named turningAngle with this code:

turningAngle = randomRealRange(0, 360);

After moving forward we will aim the turtle with code like this:


Running the example program

In the before code we prepare the (x, y) graph and send the turtle home. All is set to begin the walk.

In every cycle of the loop code we walk the turtle forward a random distance and then spin the turtle to the right a random amount.

The loop code continues to cycle in this program; so, use the 'Stop' button to quit.

The example program

Angle measurement: Degrees Radians

Go on input

Sorry, apparently this browser does not support HTML 5 canvas tag graphics.

Edit: Runtime          View: Starter Suggestion

To runtime:


Editor width: Normal Wide








Next tutorial: penUp and penDown

All contents of EZ Math Movie are copyrighted: Copyright 2011, Edward A. Zobel. All rights reserved.

Other sites you may find interesting

Zona Land Education Like Math and Physics?

Zona Land Education offers explanations, diagrams, and animations on these topics.
And it is all presented in a clear and casual manner.

Here is the link: zonalandeducation.com

EZ Programing Demos Want to learn about programing computers?

EZ Programing Demos has an animated, slow motion, interactive programing language demonstrator.
The site presents basic ideas at a beginner's level.

Here is the link: ezprogramingdemos.com

Custom Search