Perl simulation: a random walk

The tutor returns to Perl programming with a random walk simulation.

A really simple conception of a random walk is that the walker starts at 0 on the number line, then makes consecutive steps, each of which can either be left or right. The probability of left or right can be equal or different. After a certain number of steps, the position of the walker is taken.

Perl, with its rand() function, facilitates easy simulation of a random walk:

#!/usr/bin/perl
print “Welcome to the random walk simulation.\n\n”;
print “Enter the number of steps you’d like, please.\n\n”;
$steps=<STDIN>;
chomp $steps;
$pos=0;
for($i=0;$i<$steps;$i++){
$rn=int(rand(100));
if($rn % 2==0){
$pos=$pos-1;
}
else{
$pos++;
}
}
if($pos<0){ $dir="left"; $pos*=-1; }
else{
$dir=”right”;
}
print “The position, after $steps steps, is $pos units $dir\n\n”;

Next post I’ll explain this program:)

Sources:

Ross, Sheldon M. Probability Models, Fifth Ed. San Diego: Academic Press, Inc., 1993.

McGrath, Mike. Perl in easy steps. Southam: Computer Step, 2004.

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Tagged with: , , ,

Leave a Reply