Random seed at runtime

时光总嘲笑我的痴心妄想 提交于 2019-12-17 20:15:33

问题


How can I generate different random numbers at runtime?

I've tried

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.

What would you suggest me to do?


回答1:


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
}

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

Unit Tests

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?

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.




回答2:


You need to call srand once per program execution. Calling rand updates the internal state of the random number generator, so calling srand again actually resets the random state. If less than a second has passed, time will be the same and you will get the same stream of random numbers.




回答3:


srand is used to seed the random number generator. The 's' stands for 'seed'. It's called "seeding" because you only do it once: once it's "planted", you have a stream from which you can call rand as many times as you need. Don't call srand at the beginning of the function that needs random numbers. Call it at the beginning of the program.

Yes, it's a hack. But it's a hack with a very well-documented interface.



来源:https://stackoverflow.com/questions/4331371/random-seed-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!