简体   繁体   English

生成一系列随机数?

[英]Generating a series of random numbers?

(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). 此方法将几个静态变量作为参数,并返回从随机数( 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. 但是,考虑到Random类构造函数的种子基于当前系统时间,因此如果我连续25次调用该方法,则所有25次结果都可以返回75.01。

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. 保留Random类的实例,并在每次需要新的随机数时对其调用NextDouble 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... 假设您实际上已经证明您的程序可以在每次调用时获得75.01(或类似的价格)...

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). 最好的选择是,如果您担心构造函数中的种子设定,则仅创建一个Random实例,而不是为每个函数调用一次(这听起来正在发生)创建一个Random实例。 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#. 这是C#中的Mersenne Twister算法实现的链接 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. 如果您的代码对时间不太敏感(在该块上),则可以在对随机函数的调用之间赋予2ms或3ms的延迟。

HTH! HTH!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM