C# Random Numbers – How to Generate

c++random

I'm looking at generating a random number between 1 and 5 million. The process doesn't have to be quick (although it would be good if it was), but it must be as random as possible (I know nothing is random). I have a variety of data sources for the seed.

I'm not sure if the .NET Random class is going to be good enough for this.

This will be used to select a winning ticket.

Best Answer

The System.Random class probably is good enough:

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 only thing you have to watch out for is that you don't reuse the same seed too often:

If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random.

Related Question