Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How long does the stream of Random().Next() take until it repeats?

Tags:

c#

random

cycle

Consider the .NET Random stream:

var r = new Random(); 
while (true) 
{ 
    r.Next(); 
}

How long does it take to repeat?

like image 574
aharon Avatar asked Jan 12 '10 16:01

aharon


People also ask

How does random next work?

Random. Next generates a random number whose value ranges from 0 to less than Int32. MaxValue. To generate a random number whose value ranges from 0 to some other positive number, use the Random.

How will you generate a random number which does not get repeated?

We can use either the RAND or RANDBETWEEN functions for this. The RAND function is the fastest because we don't have to specify any arguments. The RAND function returns a random decimal number to the cell. Input the formula =RAND() in the first cell and double-click the fill handle to copy the formula down.

How do you repeat random numbers in Java?

Random num = new Random(); Now, in a loop, use the nextInt() method since it is used to get the next random integer value. You can also set a range, like for 0 to 20, write it as. nextInt( 20 );


1 Answers

According to the documentation:

Pseudo-random numbers are chosen with equal probability from a finite set of numbers. The chosen numbers are not completely random because a definite mathematical algorithm is used to select them, but they are sufficiently random for practical purposes. The current implementation of the Random class is based on Donald E. Knuth's subtractive random number generator algorithm. For more information, see D. E. Knuth. "The Art of Computer Programming, volume 2: Seminumerical Algorithms". Addison-Wesley, Reading, MA, second edition, 1981.

The subtractive generator (Knuth, Vol 2) Xf,n = (Xf,n-k - Xf,n-j) mod 1. See Knuth for a table of possible values of k and j. We choose k = 63, j = 31. This generator is interesting because:

  • It has a long period. The period of the least significant bit in this sequence is 2k-1. The actual period is much longer than this.
  • With some mild restrictions, the floating point arithmetic involved is exact!

The second property holds when X is of the form l 247 (0 � l < 247) Single-precision arithmetic is exact on the Crays (48-bit mantissa) and as is double-precision arithmetic on IEEE-compliant machines.

This allows the basic random number sequence to be generated by the Fortran code

  x(n) = x(n-k) - x(n-j)
  if (x(n) < 0.0) x(n) = 1.0 + x(n)

In practice random numbers are generated in batches as needed and stored in an array which acts as a circular buffer.

The algorithm mentioned has a period that depends on the seed value - you can find more details here.

like image 188
LBushkin Avatar answered Oct 07 '22 23:10

LBushkin