2

(I did a search, and didn't see a duplicate. I apologize in advance if there is one.)

I have the need to repeatedly call a method that performs some simulations. This method takes in a couple of static variables as arguments, and returns a calculated result derived from a random number (double) (0.01 - 100.00).

However, given that the Random class constructor bases its seed off of the current system time, if I call the method 25 times in a row, I could get 75.01 back as the result all 25 times.

Is there a relatively simple way to get an almost-guaranteed different number back on each method call?

I suspect this is somewhat easy to accomplish, I'm just at a loss.

Thanks!

Ian P
  • 12,840
  • 6
  • 48
  • 70
  • 1
    Just keep using the same Random instance. – Julien Roncaglia Mar 09 '11 at 16:57
  • 3
    Yes, see [this](http://stackoverflow.com/questions/2643421/random-number-generator-in-c), [that](http://stackoverflow.com/questions/932520/why-does-it-appear-that-my-random-number-generator-isnt-random-in-c) or [that one](http://stackoverflow.com/questions/3053807/random-number-in-a-loop) . This question was actually asked quiet numerous times (in different forms, though). – Bobby Mar 09 '11 at 16:57
  • 2
    Construct Random once and use the same instance for every call, rather than creating a new instance for each call. – Dan Bryant Mar 09 '11 at 16:58
  • 1
    See http://stackoverflow.com/questions/2727538/random-encounter-not-so-random (second search result for 'random c#'). – Robert Gowland Mar 09 '11 at 17:01
  • Check this link: http://geekswithblogs.net/kakaiya/archive/2005/11/27/61273.aspx – Mike Cole Mar 09 '11 at 16:59

5 Answers5

6

Keep an instance of the Random class and call NextDouble on it every time you want a new random number. You won't get the same number repeatedly.

Phil Gan
  • 2,813
  • 2
  • 29
  • 38
1

Assuming you've actually shown that your program can get 75.01 (or something like that) on every call...

You're best bet probably is to only create one instance of Random if you're concerned about the seeding in the constructor, instead of once for every function call (which is what it sounds like is currently happening). The instance would probably have to be static and private...

FrustratedWithFormsDesigner
  • 26,726
  • 31
  • 139
  • 202
1

I ran into the same problem the other day, I was reinitializing my random object and getting repeating data. Only initialize the object once and use it throughout the life of the program.

Davido
  • 2,913
  • 24
  • 38
0

Here's the link to the Mersenne Twister algorithm implementation in C#. You should be able to get it quickly

Eedoh
  • 5,818
  • 9
  • 38
  • 62
-2

if your code is not too time sensitive (on that chunk) you can tr to give 2ms or 3ms delay between the calls to the random function.

HTH!

SubniC
  • 9,807
  • 4
  • 26
  • 33