Perl random walk simulation: code explanation
The tutor continues with some explanation of last post’s Perl random walk simulation.
Below is the Perl code from last post, this time with some comments (recall that # denotes a comment in Perl):
#!/usr/bin/perl # needed for Linux (Unix)
print “Welcome to the random walk simulation.\n\n”;
print “Enter the number of steps you’d like, please.\n\n”;
$steps=<STDIN>;# <STDIN> fetches user input
chomp $steps;# chomps the newline from the input
$pos=0;# walker’s position starts as 0
for($i=0;$i<$steps;$i++){
$rn=int(rand(100)); # Perl random number function
if($rn % 2==0){# % is Perl’s modulus operator
$pos=$pos-1;
}# if the random number is even, walker steps left
else{
$pos++; # adds 1 to the $pos value
}# otherwise, walker steps right
}
if($pos<0){
$dir="left";
$pos*=-1;# means $pos=$pos*-1;
}
else{
$dir=”right”;
}
print “The position, after $steps steps, is $pos units $dir\n\n”;
This random walk is a great springboard to summer posts about probability. Of course, we never need a reason to return to Perl:)
Source:
McGrath, Mike. Perl in easy steps. Southam: Computer Step, 2004.
Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.
Leave a Reply
You must be logged in to post a comment.