Perl programming: random numbers

Tutoring math, you realize that some of your students will move on to computer science at university.  The tutor brings up a time-honoured favourite among comp-sci people:  random number generation.

Every computer programming language I know of has a random number generator.  The one I know in Perl is rand().  Common among such functions, it gives a random number between 0 and 1:  a decimal to 10 or so places.  If you want a random whole number, you can  multiply the output of rand() by 10, 100, 1000, or some other power of 10, then truncate it.  The following little program serves an example:

 
#!/usr/bin/perl

$num0=rand();

$num1=1000*$num0;

$num2=int($num1);

print “\n\nYour random number between 0 and 1000 is $num2\n\n”;

How are random numbers accomplished? There are several ways a computer might do so. A deeper question is, “How can a computer generate a truly random number, when a computer calculates numbers rather than creates them?” The answer lies in the compromise of accepting unpredictable as random.

For more about this wonderful topic, please return soon.

Source: perlmeme.org

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

Tagged with: , ,

Leave a Reply