srand()函数 - 为什么叫它只有一次? [英] srand() — why call it only once?

查看:165
本文介绍了srand()函数 - 为什么叫它只有一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这问题是关于这个问题的评论
推荐方式初始化函数srand?。第一个评论说,函数srand()应只在一个应用程序调用一次。为什么会这样呢?


解决方案

这取决于你想要达到的目的。

随机化作为具有初始值,即函数执行种子

因此​​,对于相同的种子,你总是会得到的值相同的序列。

如果您尝试每次你需要一个随机值时间设置种子,而种子是相同的号码,你总是会得到相同的随机的价值。

种子从当前时间时间(NULL),通常采取的,这是秒,为,所以如果你总是设置取随机数前的种子,你会得到相同数量的,只要你调用函数srand /兰特组合多次在同一秒

要避免这个问题,函数srand被每个应用程序设置只有一次,因为它是值得怀疑的两个应用实例将在同一第二运行,所以然后每个实例将具有随机数的不同序列。

但是,还有就是你运行你的应用程序(尤其是如果它是短暂的,或命令行工具或类似的东西)在第二多次轻微的可能性,那么你将不得不诉诸其他方式选择的种子(除非在不同的应用程序实例相同的序列是确定由你)。但就像我说的,这取决于使用的应用上下文。

此外,您还可以尝试增加precision到微秒(减少同一种子的机会),要求( SYS / time.h中

  timeval结构T1;
函数gettimeofday(&放大器; T1,NULL);
函数srand(t1.tv_usec * t1.tv_sec);

This question is about a comment in this question Recommended way to initialize srand?. The first comment says that srand() should be called only ONCE in an application. Why is it so?

解决方案

That depends on what you are trying to achieve.

Randomization is performed as a function that has a starting value, namely the seed.

So, for the same seed, you will always get the same sequence of values.

If you try to set the seed every time you need a random value, and the seed is the same number, you will always get the same "random" value.

Seed is usually taken from the current time, which are the seconds, as in time(NULL), so if you always set the seed before taking the random number, you will get the same number as long as you call the srand/rand combo multiple times in the same second.

To avoid this problem, srand is set only once per application, because it is doubtful that two of the application instances will be run in the same second, so each instance will then have a different sequence of random numbers.

However, there is a slight possibility that you will run your app (especially if it's a short one, or a command line tool or something like that) many times in a second, then you will have to resort to some other way of choosing a seed (unless the same sequence in different application instances is ok by you). But like I said, that depends on your application context of usage.

Also, you may want to try to increase the precision to microseconds (minimizing the chance of the same seed), requires (sys/time.h):

struct timeval t1;
gettimeofday(&t1, NULL);
srand(t1.tv_usec * t1.tv_sec);

这篇关于srand()函数 - 为什么叫它只有一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆