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?
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.
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.
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.
random() Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With