C++ 就生成随机数而言,种子是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14914595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is a seed in terms of generating a random number?
提问by SirRupertIII
What is a seed in terms of generating a random number?
就生成随机数而言,种子是什么?
I need to generate hundreds to thousands of random numbers, I have read a lot about using a "seed". What is a seed? Is a seed where the random numbers start from? For example if I set my seed to be 5 will it generate numbers from 5 to whatever my limit is? So it will never give me 3 for example.
我需要生成数百到数千个随机数,我已经阅读了很多关于使用“种子”的信息。什么是种子?是随机数从哪里开始的种子吗?例如,如果我将种子设置为 5,它会生成从 5 到我的限制的数字吗?所以它永远不会给我 3 例如。
I am using C++, so if you provide any examples it'd be nice if it was in C++.
我使用的是 C++,所以如果你提供任何例子,如果它是在 C++ 中就好了。
Thanks!
谢谢!
回答by 6502
What is normally called a random number sequence in reality is a "pseudo-random" number sequence because the values are computed using a deterministic algorithm and probability plays no real role.
在现实中通常称为随机数序列的是“伪随机”数序列,因为这些值是使用确定性算法计算的,而概率并没有实际作用。
The "seed" is a starting point for the sequence and the guarantee is that if you start from the same seed you will get the same sequence of numbers. This is very useful for example for debugging (when you are looking for an error in a program you need to be able to reproduce the problem and study it, a non-deterministic program would be much harder to debug because every run would be different).
“种子”是序列的起点,保证如果您从相同的种子开始,您将获得相同的数字序列。这对于调试非常有用(当您在程序中寻找错误时,您需要能够重现问题并研究它,非确定性程序将更难调试,因为每次运行都会不同) .
If you need just a random sequence of numbers and don't need to reproduce it then simply use current time as seed... for example with:
如果您只需要一个随机的数字序列并且不需要重现它,那么只需使用当前时间作为种子......例如:
srand(time(NULL));
回答by Anwarvic
So, let's put it this way:
所以,让我们这样说:
if you and your friend set the seed equals to the same number, by then you and your friend will get the same random numbers. So, if all of us write this simple program:
如果您和您的朋友将种子设置为相同的数字,那么您和您的朋友将获得相同的随机数。所以,如果我们所有人都编写这个简单的程序:
#include<iostream>
using namespace std;
void main () {
srand(0);
for (int i=0; i<3; i++){
int x = rand()%11; //range between 0 and 10
cout<<x<<endl;
}
}
We all will get the same random numbers which are (5, 8, 8).
我们都会得到相同的随机数,即 (5, 8, 8)。
And if you want to get different number each time, you can use srand(time())
如果你想每次都得到不同的数字,你可以使用srand(time())