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

Documentation for scala.util.Random.nextInt (n: Int): Int says: "Returns a pseudo random uniformly distributed int value between 0 (inclusive) and the specified value (exceptional) ...", whereas for scala.util.Random.nextInt (): Int he says: "Returns the next pseudorandom uniformly distributed int value ...", without any cost to zero. Can I get a negative value here?

+8
scala random
source share
4 answers

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

 scala> import util.Random import util.Random scala> Random.nextInt res0: Int = -299006430 
+9
source share

Yes, you can (and this is normal due to the definition of a uniform distribution). Moreover, you will receive it in almost 50% of cases.

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

gave me 49946 - which is close to 50%.

+12
source share

As you can see here (using Mike Harrah excellent sxr ), Scala Random simply delegates to the base java.util.Random called self .

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

If you only want a positive range, you can use the overloaded nextInt method, which takes an argument, for example:

 Random.nextInt(Integer.MAX_VALUE); 

According to the docs:

Returns a pseudo-random uniformly distributed int value between 0 (inclusive) and the specified value (exception), taken from this sequence of random number generators.

+7
source share

scala.uti.Random.nextInt (): Int uses the same java.util.Random method. And the range, as Luigi pointed out, is [Integer.MIN_VAL, Integer.MAX_VAL]. In fact, a โ€œuniformly distributed int valueโ€ means that any number of type int can be returned, and the probability that each of them will theoretically be the same.

+2
source share

All Articles