Can scala.util.Random.nextInt (): Int occasionally return a negative value?

As you can see here (using Mike Harrah's excellent sxr), Scala's Random just delegates to an underlying java.util.Random, which is referred to as self.

As others pointed out the default range is between Integer.MIN_VAL and Integer.MAX_VAL, in other words, any Integer possible, including the negative ones.

If you want just the positive range, you can use the overloaded method nextInt that takes an argument, like this:

Random.nextInt(Integer.MAX_VALUE);

According to the docs:

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.


Yes, you can (and that's ok due to definition of uniform distribution). Moreover you'll get it in nearly 50% of cases.

(for(i <- 1 to 100000) yield scala.util.Random.nextInt()).filter(_<0).length

have yielded for me 49946 - that's quite close to the 50%.


Apparently, yes. It returned a negative value on my first try! :-)

scala> import util.Random
import util.Random

scala> Random.nextInt
res0: Int = -299006430

Tags:

Random

Scala