Scala-native: Random without a seed is deterministic

Created on 16 Jun 2017  路  6Comments  路  Source: scala-native/scala-native

Steps to reproduce

Run the following program several times:

     val r= new java.util.Random()
     println(r.nextInt)

Observed

I keep getting the same results.
Obviously, I might be totally (un)lucky.

1206531168 the whole time

Expected

Different results each time I call it as per Random() constructor javadoc:

This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor.

bug javalib

Most helpful comment

Which begs for a reference to: https://xkcd.com/221/

All 6 comments

Which begs for a reference to: https://xkcd.com/221/

When I looked at it. the stdlib.rand yields the same results for me every time I call it:

println(scala.scalanative.native.stdlib.rand)

And there I am not fully sure how to troubleshoot further.

When running this bit of code:

for (i <- 1 to 10) println(scala.scalanative.native.stdlib.rand)

I get the following:

16807
282475249
1622650073
984943658
1144108930
470211272
101027544
1457850878
1458777923
2007237709

But if I run again:

16807
282475249
1622650073
984943658
1144108930
470211272
101027544
1457850878
1458777923
2007237709

Looking at the default Random ctor. The seed should probably be the time in Millis or something?

Keep filing those, @mccartney ! 馃憤

We should initialize srand first before calling rand. See https://www.tutorialspoint.com/c_standard_library/c_function_srand.htm

Without seeding before using rand, rand will start the same sequence on each run.

Was this page helpful?
0 / 5 - 0 ratings