5

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.

codesections
  • 8,900
  • 16
  • 50
Jim Bollinger
  • 1,671
  • 1
  • 13
  • 1
    If you are running on the same hardware and is it should – Lars Nielsen Oct 08 '22 at 05:13
  • A statistical programming language like `R` has a function `set.seed()` which enables reproducible generation of random numbers. AFAIK Raku (designed more as a general programming language) has no such feature--although a module may be designed to add it. – jubilatious1 Oct 08 '22 at 16:11
  • Issue filed: https://github.com/rakudo/rakudo/issues/5074 – raiph Oct 09 '22 at 00:30
  • 1
    This is currently very implementation-specific (and, indeed, can even vary with compiler version), so I added the `rakudo` tag. – codesections Oct 22 '22 at 22:19

2 Answers2

2

It should produce the same numbers for a given piece of code all of the time. And I haven't been able to reproduce your observation in any way.

There may be something spooky going on under the hood, though:

$ raku -e 'srand 1; (my $x = (1..1000).pick(1)).say'
(761)
$ raku -e 'srand 1; (my @x = (1..1000).pick(1)).say'
[471]

On the surface, you'd say that these values should be the same, as each only generates a single value. But apparently a different number of random values is actually calculated under the hood, causing the visibly different values. Is that perhaps what is going on in your case?

Elizabeth Mattijsen
  • 25,654
  • 3
  • 75
  • 105
1

(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.

codesections
  • 8,900
  • 16
  • 50