Alex Rivera | Logout

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

Asked 2011-10-16T11:14:59.710
10

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?

Edit
Report

2 Answers

10

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

scala> import util.Random
import util.Random

scala> Random.nextInt
res0: Int = -299006430
answered 2011-10-16T11:26:50.517
2

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.

answered 2011-10-16T13:00:48.113

Your Answer