generate reliable pseudorandom number

匆匆过客 提交于 2019-11-29 15:59:50

From the C standard (and Objective C is a thin layer on top of C so this should still hold):

If srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated.

There's no guarantee that different implementations (or even different versions of the same implementation) will give a consistent sequence based on the seed. If you really want to guarantee that, you can code up your own linear congruential generator, such as the example one in the standard itself:

// RAND_MAX assumed to be 32767.
static unsigned long int next = 1;
void srand(unsigned int seed) { next = seed; }
int rand(void) {
    next = next * 1103515245 + 12345;
    return (unsigned int)(next/65536) % 32768;
}

And, despite the fact that there are better generators around, the simple linear congruential one is generally more than adequate, unless you're a statistician or cryptographer.

If you provide a seed value to rand then it should consistently provide the same sequence of pseudorandom numbers. You can also try arc4random().

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