On Mon, 15 Jan 2007 13:14:07 -0000, "Daniel"
<Da*****@vestryonline.comwrote:
>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
You appear to have at least three PRNGs going, randomSeedm _random and
random, though the last might be a missing underscore. There is
nothing wrong with the principle of using randomSeed to generate seeds
for a set of further PRNGs, though it might be easier to just rely on
one PRNG for everything.
Without seeing the rest of your code I cannot tell why you are getting
the same set of numbers. One possibility is if min and max are too
close together then only a limited range of numbers can be returned.
If you are not happy with the standard C# PRNG, then there is the
cryptographic version:
System.Security.Cryptography.RandomNumberGenerator or
System.Security.Cryptography.RNGCryptoServiceProvi der which both point
back to the CryptAPI RNG.
RFC 4086 describes the CryptAPI RNG thus:
"The Windows CryptAPI cryptographic service provider stores a seed
state variable with every user. When CryptGenRandom is called,
this is combined with any randomness provided in the call and with
various system and user data such as the process ID, thread ID,
system clock, system time, system counter, memory status, free disk
clusters, and hashed user environment block. This data is all fed
to SHA-1, and the output is used to seed an RC4 key stream. That
key stream is used to produce the pseudo-random data requested and
to update the user's seed state variable.
"Users of Windows ".NET" will probably find it easier to use the
RNGCryptoServiceProvider.GetBytes method interface."
Note that this is a cryptographic RNG - there is no user definable
seed so you cannot generate the same set of random numbers twice.
SHA-1 is a cryptographic hash function and RC4 is a stream cypher,
which is in effect a very long period PRNG. Both are well covered in
Wikipedia if you are interested.
Alternatively you might want to write your own PRNG, then Chapter
Seven of "Numerical Recipes on C" is very helpful:
http://www.nrbook.com/a/bookcpdf.php
The code is in C and an example of the saying "Real programmers can
write Fortran in any language", but it is still a useful basis to work
from.
Knuth Volume Two is also useful for non-cryptographic PRNG background.
rossum