Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real random c# generator

Tags:

c#-4.0

  Random ran = new Random();
  byte tmp = (byte)ran.Next(10);

Is there an alternative to this code? It does not seem to have fully random behavior.

like image 795
Dominating Avatar asked May 27 '11 12:05

Dominating


2 Answers

There are multiple reasons for why this could occur. One common problem is to create multiple instances of the Random class within a program. When using the Random class you should only create one instance and generate numbers from that. The article Create better random numbers in C# has a good explanation of why and explains why not doing this could lead to a problem.

Another common scenario is accessing the Random class object from multiple threads. System.Random is not thread safe (see the Remarks section of the documentation for Random) and thus can lead to unexpected and unwanted behavior. If using it in a multi-threaded environment then you need to be sure to use some form of locking to prevent multiple threads trying to generate random numbers at the same time.

For higher degrees of security and randomness you can use a cryptographically secure random number generator like System.Security.Cryptography.RNGCryptoServiceProvider. Note that using a more secure random number generator will incur a performance penalty in comparison with System.Random.

If you don't need something cryptographically secure, but still want something that is more "random" than the Random class you can explore using other PRNG's such as Mersenne Twister. There are lots of options, each with different characteristics and performance profiles. Which you choose is heavily dependent on your goal.

like image 121
pstrjds Avatar answered Nov 03 '22 16:11

pstrjds


It might be simpler than that. If you can this method in a tight loop:

for (int i = 0; i < 1000; i++)
{
   Random ran = new Random();
   byte tmp;            
   tmp = (byte)ran.Next(10);
}

You might see the same number over and over. Make sure you create the Random object outside any sort of looping.

Random ran = new Random();

for (int i = 0; i < 1000; i++)
{
   byte tmp;            
   tmp = (byte)ran.Next(10);
}

That said, it is true that the crypto provider is better. But you're only getting randoms between 0 & 9 so how random does it have to be?

like image 21
Michael Kennedy Avatar answered Nov 03 '22 15:11

Michael Kennedy