Does stdlib's rand() always give the same sequence?

前端 未结 6 1867
甜味超标
甜味超标 2020-12-07 02:24

I quite like being able to generate the same set of pseudo-random data repeatedly, especially with tweaking experimental code. Through observation I would say that ran

6条回答
  •  不思量自难忘°
    2020-12-07 02:33

    If you are in a UNIX/Linux enviroment you can see the drand48() and srand48() at your man pages if you are not you can see online manuals for the C Language. The prototypes can be found at /usr/include/stdlib.h . The first one use the Linear Congruential Method that is frequently used in Simulations.

    If you provide the same seed to srand48() i.e. srand48(2) and then put the dran48() in a for loop then the sequence will be the same every time. i.e.

    include stdio.h
    include stdlib.h
    double drand48();
    int main(void){
        int i;
        double rn;
        srand48(2);
        for(i=0; i<10; i++){
            randNum = drand48();
            printf("%.6l\n", randNum);
            return 0;
    }
    

提交回复
热议问题