Suman
Suman

Reputation: 3545

srand in Raku, is it expected?

I am trying to run a code containing srand function:

srand(1);
my @x = (1..1000).roll(100);
my @y = (200..7000).roll(100);
say sum(@x);
say sum(@y);
say $*KERNEL

From the docs its pretty clear that srand is platform dependent. When I test this in my Windows 10, I get

46221
375477
win32

When I test it in glot.io here, I get

50941
405340
linux

in tio.run here, I get

47784
354115
linux (5.2.11.100.fc.29.x.86._.64)

in repl.it, I get enter image description here

51496
362664
linux

in raku irc channel, its

enter image description here

50941
405340
linux

So even when the platform is linux i.e $*KERNEL ~~ 'linux', there are myriads of output. Is this expected ?

Why I am asking this here is because I cannot test the following code in continuous integration (e.g. github actions) due to this variability even in linux. The following code fails in GitHub Actions:

use Test;
if $*KERNEL ~~ 'win32' {
    srand(1); # From Raku docs: Note that srand is called with a platform dependent value when a Raku program is started.
    # This is tested on my own Windows 10
    my @x = (1..1000).roll(100);
    my @y = (200..7000).roll(100);
    is sum(@x), 46221;
    is sum(@y), 375477;
}
elsif $*KERNEL ~~ 'linux' {
    srand(1); # From Raku docs: Note that srand is called with a platform dependent value when a Raku program is started.
    my @x = (1..1000).roll(100);
    my @y = (200..7000).roll(100);
    is sum(@x), 50941;
    is sum(@y), 405340;

}
else {
    skip "Not tested on Mac !", 1;
}

I want to make this test work while doing continuous integration.

Upvotes: 6

Views: 171

Answers (2)

jjmerelo
jjmerelo

Reputation: 23527

Well, srand is a low-level nqp operator. It's tested against calls to nqp::rand_n So if you do exactly the same number of calls you're bound to get the same result. I'm afraid that roll involves a random number of calls so you will not have the same result even if you do it in the same platform:

Rolling with srand

Testing the sequences obtained is, if I may, not a good strategy for testing randomness. There are many possible strategies for doing it, some of them are featured here TDD for a random algorithm In general, you should check for what random feature you want out of it: if you want a (rough) uniform distribution, you should check for that, or if you want anything else, ditto. In this case it's likely that what you want is to have a gaussian distribution of sums, maybe the easiest thing would be to check that the histogram follows roughly a bell curve.

Upvotes: 6

Elizabeth Mattijsen
Elizabeth Mattijsen

Reputation: 26924

I think the only thing setting srand guarantees you, is a repeatable random sequence on that particular combination of hardware / OS / software. That's it.

Perhaps a Raku module can serve your need better.

Upvotes: 4

Related Questions