运行时随机种子 [英] Random seed at runtime

查看:128
本文介绍了运行时随机种子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在运行时生成不同的随机数?

How can I generate different random numbers at runtime?

我尝试过

srand((unsigned) time(0));

但是似乎在每次启动程序时我都会得到一个随机数,但是在函数本身的每次执行时却没有得到一个随机数...

But it seems to get me a random number on every startup of the program, but not on every execution of the function itself...

我正在尝试使用随机数,随机迭代,元素数量等使某些测试自动化...我以为我可以打电话

I'm trying to automate some tests with random numbers, random iterations, number of elements, etc... I thought I could just call

srand((unsigned) time(0));

在我的测试功能和宾果游戏开始时,但显然没有.

at the beginning of my test function and bingo, but apparently not.

您建议我做什么?

推荐答案

srand()

正如其他人所提到的. srand()播种随机数生成器.这基本上意味着它设置了随机数序列的起点.因此,在真实的应用程序中,您希望调用一次(通常是您在main中所做的第一件事(在设置区域设置之后)).

srand()

As others have mentioned. srand() seeds the random number generator. This basically means it sets the start point for the sequence of random numbers. Therefore in a real application you want to call it once (usually the first thing you do in main (just after setting the locale)).

int main()
{
    srand(time(0));

    // STUFF
}

现在,当您需要随机数时,只需调用rand().

Now when you need a random number just call rand().

进行单元测试.在这种情况下,您实际上并不需要随机数.非确定性的单元测试浪费时间.如果失败了,您将如何重现结果以进行修复?

Moving to unit testing. In this situation you don;t really want random numbers. Non deterministic unit tests are a waste of time. If one fails how do you re-produce the result so you can fix it?

您仍然可以在单元测试中使用rand().但是,您应该使用srand()对其进行初始化,以便在调用rand()时,单元测试 ALWAYS 始终具有相同的值.因此,测试设置应在每次测试之前调用srand(0)(或除0以外的某个常数).

You can still use rand() in the unit tests. But you should initialize it (with srand()) so that the unit tests ALWAYS get the same values when rand() is called. So the test setup should call srand(0) before each test (Or some constant other than 0).

您需要在每次测试之前调用它的原因是,以便当您调用单元测试框架以仅运行一个测试(或一组测试)时,它们仍使用相同的随机数.

The reason you need to call it before each test, is so that when you call the unit test framework to run just one test (or one set of tests) they still use the same random numbers.

这篇关于运行时随机种子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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