开发者

Generating a series of random numbers?

开发者 https://www.devze.com 2023-02-15 16:23 出处:网络
(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 sta

(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, g开发者_如何学Goiven 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!


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.


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


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.


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


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消