Velocity Reviews > Random NOt random?

# Random NOt random?

Darren Clark
Guest
Posts: n/a

 06-24-2004

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
Guest
Posts: n/a

 06-24-2004
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" <(E-Mail Removed)> ¦b¶l¥ó
news:%(E-Mail Removed) ¤¤¼¶¼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?
>
>

MattC
Guest
Posts: n/a

 06-24-2004
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" <(E-Mail Removed)> wrote in message
news:#(E-Mail Removed)...
>
>
> 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?
>
>

mikeb
Guest
Posts: n/a

 06-24-2004
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