[英]using the time function for srand in pseudo-random number generator in c
#include <time.h>
((unsigned)time(NULL));
I don't understand why you have to include the time header file and use the time function in your program when creating a pseudo-random number generator using the function srand(). 我不明白为什么在使用函数srand()创建伪随机数生成器时,为什么必须在程序中包括时间头文件并使用时间函数。 Can somebody please explain what the significance of time is in this case?
在这种情况下,有人可以解释一下时间的重要性吗?
* Please note that the code shown is only part of the program. *请注意,显示的代码仅是程序的一部分。 Thank you.
谢谢。
It's because of the Pseudo- part of Pseudorandom . 这是因为Pseudorandom的Pseudo- part。 The PRNG performs a mathematical operation upon an internally-stored seed value to yield the next output number and transform the seed.
PRNG对内部存储的种子值执行数学运算,以产生下一个输出数字并转换种子。
If you don't call time(NULL)
or some other source of entropy (eg. /dev/rand
), then the sequence will still be pseudo-random (not easily predictable by examining the values), but it will be exactly the same for every run of the program. 如果您不调用
time(NULL)
或其他熵源(例如/dev/rand
),则该序列仍将是伪随机的 (通过检查这些值不容易预测),但它将完全是每次运行该程序都相同。 Because, even though it may be very difficult to accurately predict the next number, it is possible because the PRNG is deterministic . 因为即使精确地预测下一个数字可能非常困难,但由于PRNG是确定性的 ,因此这是可能的。
If you don't provide your own seed with srand()
, the default initial seed is usually 1 . 如果您不为自己的种子提供
srand()
,则默认的初始种子通常为1 。
The time()
call provides the initial source of entropy that makes the starting seed unpredictable. time()
调用提供了使初始种子无法预测的熵的初始来源 。
It makes the code non-repeatable when it is called for a second time. 当第二次调用该代码时,它将使该代码不可重复。 If you include no seed or a fixed number for a seed, the program will act exactly the same, because the random number will be the same.
如果您不包括种子,也没有固定数量的种子,则该程序将执行完全相同的操作,因为随机数将相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.