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!

5
  • 1
    Just keep using the same Random instance. Commented Mar 9, 2011 at 16:57
  • 3
    Yes, see this, that or that one . This question was actually asked quiet numerous times (in different forms, though). Commented Mar 9, 2011 at 16:57
  • 2
    Construct Random once and use the same instance for every call, rather than creating a new instance for each call. Commented Mar 9, 2011 at 16:58
  • Check this link: geekswithblogs.net/kakaiya/archive/2005/11/27/61273.aspx Commented Mar 9, 2011 at 16:59
  • 1
    See stackoverflow.com/questions/2727538/… (second search result for 'random c#'). Commented Mar 9, 2011 at 17:01

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It was something obvious. Thanks!
@Ian P: No worries. I seem to remember the Random class in .net behaving differently than I expected the first time I used it too.
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...

Comments

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.

Comments

0

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

Comments

-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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.