Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

random

scala

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?

like image 765
Ivan Avatar asked Oct 16 '11 11:10

Ivan


People also ask

Does nextInt () return negative?

No, nextInt() -- the way you are calling it -- does not return negative numbers.

What is nextInt in Scala?

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

Is random nextInt inclusive?

nextInt(int n) : The nextInt(int n) is used to get a random number between 0(inclusive) and the number passed in this argument(n), exclusive.

What does random nextInt return in Java?

nextInt. Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. The general contract of nextInt is that one int value is pseudorandomly generated and returned.


2 Answers

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

like image 62
om-nom-nom Avatar answered Oct 20 '22 23:10

om-nom-nom


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

scala> import util.Random
import util.Random

scala> Random.nextInt
res0: Int = -299006430
like image 24
missingfaktor Avatar answered Oct 21 '22 00:10

missingfaktor