Ivan
Ivan

Reputation: 64227

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

Documentation for scala.util.Random.nextInt (n: Int): Int says "Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)..." while for scala.util.Random.nextInt (): Int it says "Returns the next pseudorandom, uniformly distributed int value...", without saying anything about the zero. Can I get a negative value here occasionally?

Upvotes: 10

Views: 17626

Answers (4)

Pablo Fernandez
Pablo Fernandez

Reputation: 105238

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.

Upvotes: 10

Clark Bao
Clark Bao

Reputation: 1693

scala.uti.Random.nextInt (): Int leverages the same method of java.util.Random. And the range as Luigi pointed out is [Integer.MIN_VAL,Integer.MAX_VAL]. Actually "uniformly distributed int value" means any number of int type is possible to be returned and the chance of each one in theory to be the same.

Upvotes: 2

om-nom-nom
om-nom-nom

Reputation: 62835

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%.

Upvotes: 12

missingfaktor
missingfaktor

Reputation: 92076

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

scala> import util.Random
import util.Random

scala> Random.nextInt
res0: Int = -299006430

Upvotes: 10

Related Questions