weak random ?

  • Thread starter Thread starter user
  • Start date Start date
U

user

Hello
i call it in almost same time (from two different threads):
Random rand = new Random();
id=rand.Next(65535);

and i often receive the same results.
Is it possible ? How windows count this random ?


Thanx
 
The Random class doesn't really produce random numbers. It produces
seemingly random numbers using a formula and a starting number. If you
use the same starting number, you will get the same sequence of numbers.
The get better "randomness" I prefer to use this way of initializing
Random by using DateTime.Now's Tick property.

Random rand = new Random((int)DateTime.Now.Ticks);

Happy coding!
Morten
 
Well from the docs:

Random rand = new Random();
Initializes a new instance of the Random class, using a time-dependent
default seed value.

If two threads are running simultaneously and executes this call with only
microseconds in time difference, you will definately get the same random
sequence.

Make sure there is a delay between the instantiation of the calls for the
two threads and you should be fine.


Arild
 
Even given that, we noticed a distinct pattern in random when we were using
it, and ended up calling it 6 or 7 times just to kick start it into some
degree of unpredictability. If you actually need a proper random number
generator (for encryption etc, where it could matter) you might check out
the Boost libraries - they have some good stuff.

Steve
 
If you are looking for a stronger Random generator, you should look at:

System.Security.Cryptography.RNGCryptoServiceProvider

José
 
Hello
i call it in almost same time (from two different threads):
Random rand = new Random();
id=rand.Next(65535);

and i often receive the same results.
Is it possible ? How windows count this random ?

Thanx

Random is *not* a random number generator, but rather a *pseudo* random number
generator. Given the same seed, it will always produce the same number
sequence.

From the help:
The random number generation starts from a seed value. 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.

The trick is to use a random seed. In your case, a good candidate for the seed
might be the thread id.
 
Back
Top