How random is Random()

D

Daniel

Hey guys

Using Random(), how random is it, is it possible to be predicted? I have a
requirement for a very good random number generator. I was doing something
such as:

Random randomSeed = new Random((int)_seedTimer.ElapsedTicks);
_random = new Random(randomSeed.Next(0,99999999));

return random.Next(min, max);

But i am finding that in some cases the same sets of numbers appear or
regularly occur? any idea why? Any tips on better methods for truly random
numbers?

Thanks
 
M

Marc Gravell

Well, how about let it worry about the (time-based) seed using the
default ctor? Note that in either strategy Random instances created
within a similar time range will get the same seed due to the inherent
accuracy of the system timer (not very); your best approach when
generating lots of random numbers is to keep re-using an instance
(within a thread or allowing for locking) rather than creating lots of
Randoms...

Marc/
 
M

Marc Gravell

Or as an alternative, how about something along the lines of below;
allows (thread-sync'd) access to a shard instance for simple usage, or
a Create method for creating standalone Ranom instances, but with a
seed based on the overall (static) random - i.e. calling .Create()
repeatedly within microseconds will never [singing: well hardly ever!]
return the same seeds.

Marc

static class RandomUtil
{
private readonly static Random rand = new Random();
static int Next()
{
lock (rand)
{
return rand.Next();
}
}
static Random Create()
{
return new Random(Next());
}
}
 
C

Carl Daniel [VC++ MVP]

Daniel said:
Hey guys

Using Random(), how random is it, is it possible to be predicted? I
have a requirement for a very good random number generator. I was
doing something such as:

Random randomSeed = new
Random((int)_seedTimer.ElapsedTicks); _random = new
Random(randomSeed.Next(0,99999999));
return random.Next(min, max);

But i am finding that in some cases the same sets of numbers appear or
regularly occur? any idea why? Any tips on better methods for truly
random numbers?

As others have replied, Random instances with time corellated seeds will
generate time corellated values. The Random class is a simple linear
congruential generator [1]. If you need random numbers for a security
purpose (e.g. encryption keys), then you need to use a cryptographically
strong random number generator. One such strong random number generator is
exposed by the System.Security.Cryptography.RNGCryptoServiceProvider class
[2].

-cd

[1] http://en.wikipedia.org/wiki/Linear_Congruential_Generators
[2]
http://msdn2.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top