Search code examples
randomrakusrandrakudo

Shouldn't the same srand value produce the same random numbers?


When I repeatedly run this code,

srand 1;
my @x = (1..1000).pick: 100;
say sum @x;

I get different answers each time. If I'm resetting with srand why shouldn't it produce the same random numbers each time?

The error occurs in the REPL.

The error occurs in this file:

use v6.d;

srand 1;
my $x = rand;
say $x; # OUTPUT: 0.5511548437617427

srand 1;
$x = rand;
say $x; # OUTPUT: 0.308302962221659

say $*KERNEL;  # OUTPUT: darwin

I'm using:

Welcome to Rakudo™ v2022.07. Implementing the Raku® Programming Language v6.d. Built on MoarVM version 2022.07.


Solution

  • (This answer is a paraphrase of jnthn's comment in the GitHub issue opened based on this question).

    Setting srand 1 will cause the same sequence of random numbers to be generated -- that is, the nth random number will be the same. However, since Raku (really, Rakudo and/or MoarVM, assuming you're using those backends) uses random numbers internally, you won't always be in the same position in that sequence (i.e., your n might be different) and thus you might not get the same random number.

    This is further complicated by Rakudo's optimizer. Naively, repeating the same code later in the program should consume the same number of random numbers from the sequence. However, the optimizer may well remove some of those random number uses from subsequent calls, which can result in different random numbers.

    I'm unclear to what degree the current behavior is intended versus a bug in Rakudo/MoarVM's implementation; please see the previously linked issue for additional details.