1. Perl
  2. builtin functions
  3. here

rand function - generate random numbers

Use the rand function to generate a random number . A number greater than or equal to 0, which is less than the number specified by the argument, is randomly generated.

$ret = rand 10;

Random numbers are random numbers. When creating an application, sometimes you want a random number. It is used when throwing dice and giving quizzes in the game. It is also used to create keys for encrypting data.

If you specify "10" in the rand function, for example, "2.34 ...", "5.36 ...", "9.45 ...", etc., which are greater than or equal to 0 and less than 10 are generated.

Example

This is an example that uses the random numbers generated by the rand function.

use strict;
use warnings;

print "(1) Generate a random number. (Integer less than or equal to 10)\n";
for my $i (1 .. 10) {
  # rand function returns a random number less than the argument
  print "$i times:". Int (rand 10) . "\n";
}
print "\n";

print "(2) Randomly select the elements of the array.\n";
my @members = qw/aya toru kato kenji mina haruna kita michel kotaro/;
for my $i (1 .. 10) {
  # @members is the number of elements in the array
  print "$i times:". $members[int(rand scalar @members)] . "\n";
}

Code explanation

Generate random numbers

rand(10);

Use the = rand function to generate random numbers. The rand function returns a random decimal number that is greater than or equal to 0 and less than the integer given by the argument.

If 10 is given, a random decimal number greater than or equal to 0 and less than 10 will be returned. Note that 10 is not included. 9.99999 may be returned, but 10 will not be returned.

int(rand 10);

You can get only the integer part by using int function. You can get integers from 0 to 9 with int(rand 10).

Randomly select elements of the array

my @members = qw/aya toru kato kenji mina haruna kita michel kotaro/;
$members[int(rand scalar @members)];

To randomly select the elements of array, give the number of elements in the array to the rand function, extract the integer part with the int function, and add subscripts. You can do it.

If the elements of the array are 10, random numbers from 0 to 9 will be generated and the corresponding elements will be returned.

To generate reproducible random numbers

To generate reproducible random numbers, give srand function an appropriate number before calling the rand function.

# Initialize random number generation algorithm
srand $seed;
rand $num;

How to find accurate pseudo - random numbers

If you want to find a random number that is more accurate than Perl's rand function, it is convenient to use Math::Random::MT module available on CPAN.

A method called the "Mersenne Twister method" is used to obtain accurate random numbers.

Related Informatrion