#include <stdlib.h> int rand(void); void srand(unsigned int seed); [[deprecated]] int rand_r(unsigned int *seedp);
glibc 向けの機能検査マクロの要件 (feature_test_macros(7) 参照):
rand_r():
Since glibc 2.24:
_POSIX_C_SOURCE >= 199506L
glibc 2.23 and earlier
_POSIX_C_SOURCE
srand() 関数は、 rand() 関数で作られる疑似乱数整数系列の新しい種として、 その引数の値を使用する。 これらの関数を使用して作られた疑似乱数系列は、 同じ値を引数として srand() を呼ぶことで、 再現することが可能である。
種の値が与えられない場合には、 rand() 関数は 自動的に 1 を種とする。
rand() 関数は再入可能 (reentrant) ではない。この関数には隠し状態があり、呼び出される度にこの隠し状態が変更されるからである。ちょうどこの隠し状態が次の呼び出し時の乱数の種として使われるようなものである。実際にはもう少し複雑かもしれないが。スレッドを使用するアプリケーションで再現可能な動作をさせたい場合には、この状態を明示的に指定できなければならない。これを行うには、再入可能な rand_r() 関数を使用する。
Like rand(), rand_r() returns a pseudo-random integer in the range [0,~RAND_MAX]. The seedp argument is a pointer to an unsigned int that is used to store state between calls. If rand_r() is called with the same initial value for the integer pointed to by seedp, and that value is not modified between calls, then the same pseudo-random sequence will result.
rand_r() の seedp 引数が指す値により提供される状態は非常に小さな空間 なので、この関数は弱い疑似乱数生成器になってしまう。 代わりに drand48_r(3) を使ってみるとよい。
| インターフェース | 属性 | 値 |
| rand(), rand_r(), srand() | Thread safety | MT-Safe |
static unsigned long next = 1;
/* RAND_MAX assumed to be 32767 */
int myrand(void) {
next = next * 1103515245 + 12345;
return((unsigned) (next/65536) % 32768);
}
void mysrand(unsigned int seed) {
next = seed;
}
The following program can be used to display the pseudo-random sequence produced by rand() when given a particular seed. When the seed is -1, the program uses a random seed.
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
int r;
unsigned int seed, nloops;
if (argc != 3) {
fprintf(stderr, "Usage: %s <seed> <nloops>\n", argv[0]);
exit(EXIT_FAILURE);
}
seed = atoi(argv[1]);
nloops = atoi(argv[2]);
if (seed == -1) {
seed = arc4random();
printf("seed: %u\n", seed);
}
srand(seed);
for (unsigned int j = 0; j < nloops; j++) {
r = rand();
printf("%d\n", r);
}
exit(EXIT_SUCCESS);
}