在同一个程序中调用srand()两次 [英] Calling srand() twice in the same program

查看:572
本文介绍了在同一个程序中调用srand()两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么是当我调用srand()在2非常不同的点,它导致数字不是随机的?一旦我删除其中的一个,它会恢复正常。

why is it when i call srand() at 2 very different points it cause numbers to not be random? Once i remove one of them it goes back to normal.

推荐答案

这取决于你如何调用它。 srand()的目的是为 rand()使用的伪随机数生成器。因此,当你调用 srand(i)时,它会将 rand()初始化为一个固定的序列, c $ c> i 。所以当你用相同的种子重新种子,你开始得到相同的序列。

It depends on how you call it. The purpose of srand() is to seed the pseudo-random number generator used by rand(). So when you call srand(i), it will initialise rand() to a fixed sequence which depends on i. So when you re-seed with the same seed, you start getting the same sequence.

最常见的用例是种子生成器只有一次, 随机值(例如惯用的 time(NULL))。

The most common use case is to seed the generator just once, and with a suitable "random" value (such as the idiomatic time(NULL)). This guarantees makes it likely that you'll get different sequences of pseudo-random numbers in different program executions.

但是,有时候你可能会使用不同的程序来执行不同的伪随机数字序列。

However, occasionally you might want to make the pseudo-random sequence "replayable." Imagine you're testing several sorting algorithms on random data. To get fair comparisons, you should test each algorithm on the exact same data - so you'll re-seed the generator with the same seed before each run.

在其他词语:如果你想要的数字只是伪随机,种子一次,并尽可能随机的值。如果你想要一些控制&可重播性,必要的种子。

In other words: if you want the numbers simply pseudo-random, seed once, and with a value as random as possible. If you want some control & replayability, seed as necessary.

这篇关于在同一个程序中调用srand()两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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