📘 Generating random numbers using Perl 6

Generate a random number between 0 and N.

Use the randmethod, which returns a random number between 0 and the value of its invocant:

say 1.rand;   # between 0 and 1
say 2.5.rand; # between 0 and 2.5
say pi.rand;  # between 0 and 3.14…

The rand method is defined in the Cool class, which is the base class for the IntNum, and Rat types. It always returns a floating-point value of the Num data type.

To generate random integer numbers, call the Int method:

say 10.rand.Int; # Either 0, or 1, 2, 3, 4, 5, 6, 7, 8, or 9 but not 10

The srand function initializes the random numbers generator. The function expects an integer argument:

srand(1);

After setting the seed, the rand method starts generating numbers in the same sequence.

srand(1);
my $a = 10.rand;

srand(1);

my $b = 10.rand;
say $a == $b; # True 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s