随机整数 c++
我正在尝试生成随机整数(均匀分布)。 我在其他论坛上找到了这个片段,但它的工作方式非常奇怪。
srand(time(NULL));
AB=rand() % 10+1;
使用这种方法,我在一个循环中获取值,因此该值随着每次调用而增加,直到再次下降。我想这与使用时间作为初始化器有关? 这样的东西就出来了。
1 3 5 6 9 1 4 5 7 8 1 2 4 6 7.
不过,我想得到完全随机的数字,例如
1 9 1 3 8 2 1 7 6 7 5...
感谢您的帮助
I'm trying to produce random integers (uniformly distributed).
I found this snippet on an other forum but it works in a very weird way..
srand(time(NULL));
AB=rand() % 10+1;
Using this method I get values in a cycle so the value increases with every call until it goes down again. I guess this has something to do with using the time as aninitializer?
Something like this comes out.
1 3 5 6 9 1 4 5 7 8 1 2 4 6 7.
I would however like to get totally random numbers like
1 9 1 3 8 2 1 7 6 7 5...
Thanks for any help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
每个程序只应调用 srand() 一次。
You should call
srand()
only once per program.另请查看 Boost 随机数库:
Boost 随机数库< /a>
Also check out the Boost Random Number Library:
Boost Random Number Library
某些随机数生成器在使用“低位数字”时存在问题,并且存在偏差
如果您不删除某些数字,则可以解决这两个问题:
some random number generators have a problem with using "low digit", and there is a bias
if you don't drop some number, a possible work around for both issues:
您可以使用 Park-Miller“最低标准”线性同余生成器 (LCG):(seed * 16807 mod(2^31 - 1))。我的实现在这里
g++ 4.4.5 的随机整数
C 语言 'srand()' 函数用于设置全局变量 'rand( )' 使用。当您需要单个随机数序列时,“rand()”就足够了,但通常您需要多个随机数生成器。对于这些情况,我的建议是使用 C++ 和像“rand31pmc”这样的类。
如果你想生成小范围内的随机数,那么你可以使用这里提供的Java库实现:
http://docs。 oracle.com/javase/7/docs/api/java/util/Random.html#nextInt%28int%29
You can use the the Park-Miller "minimal standard" Linear Congruential Generator (LCG): (seed * 16807 mod(2^31 - 1)). My implementation is here
Random integers with g++ 4.4.5
The C language 'srand()' function is used to set the global variable that 'rand()' uses. When you need a single sequence of random numbers, 'rand()' is more than enough, but oftentimes you need several random number generators. For those cases, my advice would be to use C++ and a class like 'rand31pmc'.
If you want to generate random numbers in a small range, then you can use the Java library implementation available here:
http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt%28int%29