📘 Generating random numbers using Perl 6

📘 Generating random numbers using Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.


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

Your email address will not be published. Required fields are marked *