Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random numbers using C#

Tags:

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.

like image 999
LiamB Avatar asked Feb 14 '10 16:02

LiamB


People also ask

What does rand () do C?

rand() function is an inbuilt function in C++ STL, which is defined in header file <cstdlib>. rand() is used to generate a series of random numbers. The random number is generated by using an algorithm that gives a series of non-related numbers whenever this function is called.

Is rand () truly random?

However, the numbers generated by the rand() are not random because it generates the same sequence each time the code executed.

Does rand () generate 0 C?

rand() in C/C++ gives a number between 0 and RAND_MAX, which is guaranteed to be at least 32767.


2 Answers

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.

like image 193
ChrisF Avatar answered Nov 15 '22 15:11

ChrisF


If you need cryptographic random number, go with the System.Security.Cryptography.RNGCryptoServiceProvider class or use the RandomNumberGenerator.Create() factory method to create the default configured random number generator.

like image 29
Steven Avatar answered Nov 15 '22 17:11

Steven