Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is O(n) for java.util.Random.next(n)

I want to know whether java.util.Random.next(n) scales linearly with n or is a constant? Could someone help me with this or show me how to go about determining the complexity?

like image 365
Krish Srinivasan Avatar asked Dec 24 '13 16:12

Krish Srinivasan


People also ask

Does random next int include 0?

The nextInt(int n) method is used to get a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

Does random nextInt include 0?

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 is util random in java?

The java.util.Random class instance is used to generate a stream of pseudorandom numbers.Following are the important points about Random − The class uses a 48-bit seed, which is modified using a linear congruential formula.

Does random in java include 0?

random() Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.


2 Answers

From the docs:

Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.

According to the docs the java.util.Random.next is implemented as follows

synchronized protected int next(int bits) {
   seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
   return (int)(seed >>> (48 - bits));
 }

So the complexity is O(1)

On a side note:-

You can use several tools which are there to measure the complexity with a micro-benchmark. You can find a list over here. However if the runtime complexity is important to you you can use the Fast Mersenne Twister.(This is an external library to measure the runtime complexity as Javas random number generators are quite fast, but statistically bad)

like image 77
Rahul Tripathi Avatar answered Oct 16 '22 23:10

Rahul Tripathi


The Javadoc of next explains

The method next is implemented by class Random by atomically updating the seed to

(seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)

and returning

(int)(seed >>> (48 - bits))

Clearly, there is no trace of O(n) complexity in these expressions.

like image 24
Marko Topolnik Avatar answered Oct 17 '22 00:10

Marko Topolnik