Jim Bollinger
Jim Bollinger

Reputation: 1815

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.

Upvotes: 5

Views: 181

Answers (2)

codesections
codesections

Reputation: 9600

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

Upvotes: 1

Elizabeth Mattijsen
Elizabeth Mattijsen

Reputation: 26969

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?

Upvotes: 2

Related Questions