- Perl ›
- builtin functions ›
- here

## srand function - generates reproducible random numbers

You can use the ** srand function ** to generate reproducible random numbers. Before calling rand function, give an appropriate number to the srand function.

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

#### What is random number generation in a computer?

Computers generate random numbers by arithmetic. So this is not a random number. Computers cannot generate a random distribution like humans throw dice.

All a computer can do is create a sequence of numbers using an "algorithm that produces as even a distribution as possible". This algorithm changes the distribution depending on the difference in the initial value. This is called a pseudo-random number.

Changing the distribution depending on the difference in the initial values means that if the initial values are the same, the distribution will not change.

The rand function seems to generate a different sequence of random numbers each time because it is implicitly initialized by the srand function when it is first used. A different initial value is used each time the program is run.

By fixing the initial value given to srand, it is possible to generate reproducible random numbers.

### Example program

use strict; use warnings; print "(1) Generate reproducible random numbers.\n"; print "Generation of random number sequence (1st time)\n"; # Used to initialize random number generation algorithm (seed means seed) my $seed = 12314; # Initialize random number generation algorithm srand $seed; for my $i (1 .. 10) { print "$i times:". Int (rand 100) . "\n"; } print "\n"; print "Generate random number sequence (2nd time)\n"; # Initialize random number generation algorithm srand $seed; for my $i (1 .. 10) { print "$i times:". Int (rand 100) . "\n"; } print "\n";