# Random NOt random?

Discussion in 'ASP .Net' started by Darren Clark, Jun 24, 2004.

1. ### Darren ClarkGuest

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?
Darren Clark, Jun 24, 2004

2. ### Lau Lei CheongGuest

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

"Darren Clark" <> ¦b¶l¥ó
news:% ¤¤¼¶¼g...
>
>
> 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?
>
>
Lau Lei Cheong, Jun 24, 2004

3. ### MattCGuest

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
"Darren Clark" <> wrote in message
news:#...
>
>
> 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?
>
>
MattC, Jun 24, 2004
4. ### mikebGuest

Darren Clark wrote:
> 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.

--
mikeb
mikeb, Jun 24, 2004