I'm fairly new to scala so this might be a stupid question. I know when you do nextInt(seed)
it uses the seed but when you create the object, what is the seed for? For example in this line of code:
val rnd = new scala.util.Random(1000)
this seems to have no affect on the outcome of the numbers when you go on to use rnd.nextInt(100)
or similar.
When calling nextInt(n)
, n
is not the seed, it is the upper limit of the returned pseudo-random number (0 until n).
When creating an instance of Random
, the number you pass is the seed. It does have effect on the outcome:
val r1 = new scala.util.Random(1)
r1.nextInt(1000) // -> 985
val r2 = new scala.util.Random(2)
r2.nextInt(1000) // -> 108 - different seed than `r1`
val r3 = new scala.util.Random(1)
r3.nextInt(1000) // -> 985 - because seeded just as `r1`
The seed is never directly observable in the returned numbers (other than them following a different sequence), because a) it is internally further scrambled, b) the generated numbers use a combination of multiple bitwise operations on the seed.
Typically you will either use an arbitrary fixed number for the seed, in order to guarantee that the produced sequence is reproducible, or you use another pseudo-random number such as the current computer clock (System.currentTimeMillis
for example).