Random NOt random?

D

Darren Clark

I do the following in code

int count = randata.ProductTable.Rows.Count;

Random r = new Random();

Random r2 = new Random();

int i = r.Next(1,count);

int x = r2.Next(1,count);





and i and x will always be the same....



how does that work?
 
L

Lau Lei Cheong

Have you run r.Random() and r2.Random before?

Certainly you have to initialize random number generator before use it.

Note that if you want to use Random() function instead of the object, you
still need to run Randomize statement first.

Regards,
Lau Lei Cheong
 
M

MattC

I read somewhere that Random is only random if a subsequent call is a
certain amount of time after. Something to do with it being linked to the
clock cycle of which the lowest granularity is ms and as you can do both
calls in one cycle you get teh same number. Put a Sleep() inbetween to
force a context switch and see what happens then.

MattC
 
M

mikeb

Darren said:
I do the following in code

int count = randata.ProductTable.Rows.Count;

Random r = new Random();

Random r2 = new Random();

int i = r.Next(1,count);

int x = r2.Next(1,count);

and i and x will always be the same....

The Random class's generator depends entirely on the seed used to
initialize it - 2 generator instance initialized with the same seed will
produce the exact same sequence. At times this is what you want (for
example, when testing you might want to be able to reproduce results).

The Random() constructor you're calling uses the system clock as a seed.
Since the 2 calls are so close together in time it's very, very likely
that they will have the same seed.

See the docs for Random( int) for information on how to avoid this problem.

Also, the Random class is not a particularly good RNG - it's good enough
maybe for games and simple simulations, but if you want a really good
set of random bits look at the RNGCryptoServiceProvider class.
 

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

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top