Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random.Next returns always the same values [duplicate]

Tags:

c#

random

math

This is really weird, and I cannot see why this is happening. In the foreach cycle, I am iterating through a class A collection, and for each class, I call the Count() method, where r1 and r2 numbers are generated from 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 ones will be returned from following instances. Please, could you tell me why this is happening? Also, I cannot get different results in each class A instance. 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();  } } 
like image 529
Thomas Avatar asked Oct 31 '09 16:10

Thomas


People also ask

What does a random object next method return?

Next() Returns a non-negative random integer.

Can random numbers repeat?

The numbers generated are not truly random; typically, they form a sequence that repeats periodically, with a period so large that you can ignore it for ordinary purposes. The random number generator works by remembering a seed value which it uses to compute the next random number and also to compute a new seed.

How to use next in c#?

Next() Method This method is used to returns a non-negative random integer. Syntax: public virtual int Next (); Return Value: This method returns the 32-bit signed integer which is greater than or equal to 0 and less than MaxValue.

How do you generate random age in Python?

So for instance: random. seed() # you need to seed the random number generator n = random. randint(1, 100) if n < age: print("I am younger than you.") elif n > age: print("I am older than you.") else: print("We are the same age.")


2 Answers

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

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

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

like image 198
Guffa Avatar answered Sep 18 '22 21:09

Guffa


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 rather than -1,0

like image 37
tvanfosson Avatar answered Sep 16 '22 21:09

tvanfosson