Random.Next always returns the same values.

This is really strange, and I do not understand why this is happening. In the foreach loop, I repeat through a collection of class A, and for each class I call the Count() method, where the numbers r1 and r2 generated from the range [-1,1]. The problem is that Random.Next returns the same "random" numbers for each instance. When the results for the first instance are 0 and -1, the same will be returned from the following instances. Please could you tell me why this is happening? In addition, I cannot get different results in each instance of class A. This is the code:

 class a { Random rnd = new Random(); private void Count() { int r1 = rnd.Next(-1, 1); int r2 = rnd.Next(-1, 1); } } class b { List<a> listofA=new list<a>(); foreach (a ACLASS in listofA) { ACLASS.Count(); } } 
+44
math c # random
Oct 31 '09 at 16:41
source share
4 answers

The problem is that you are creating instances of the Random class too close to time.

When you create a Random object, it is seeded with a value from the system clock. If you create Random instances too close to time, they will all be seeded with the same random sequence.

Create a single Random object and pass its reference to the constructor when creating instances of class "a" instead of creating one Random object for each instance of "a".

+89
Oct 31 '09 at 16:46
source share

You create a new instance of Random very close to each other (your loop is very tight), so each instance effectively uses the same initial value.

The best approach would be to create one instance and pass it to your Count method.

You probably know this next bit, but I will include it here for completeness:

MSDN contains information about this, but basically your problem is the Random.Next that you use generates:

A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values ​​includes minValue, but not maxValue. If minValue is equal to maxValue, minValue is returned.

because of this, your calls will return -1 or 0.

+8
Oct 31 '09 at 16:48
source share

Use a single, static random number generator for all instances of the class.

 class a { private static Random rnd; static a() { rnd = new Random(); } private void Count() { int r1 = rnd.Next(-1, 2); int r2 = rnd.Next(-1, 2); } } 

Note the change to give you numbers in the range -1.1, not -1.0

+7
Oct 31 '09 at 16:52
source share

You include a random instance for each instance of A. It appears that they all get the same initial default value. You probably want to make a static random case for all instances of A and reuse it or alternatively provide the initial value to the instance of Random () in constructor A.

+4
Oct 31 '09 at 16:47
source share



All Articles