rand() function in C is not random even when seeded

后端 未结 2 1322
星月不相逢
星月不相逢 2020-12-11 06:37

This is most likely a machine dependent issue but I can\'t figure out what could be wrong.

#include 
#include 
#include 

        
2条回答
  •  生来不讨喜
    2020-12-11 07:22

    1. rand() is quite bad, avoid it if possible. In any good RNG the first values will be indistinguishable from random even when the seed is close (hamming distance). In rand this is not the case.
    2. If you must use rand then seed it, preferably with something higher entropy than time, and call rand() multiple times instead of reseeding-calling-reseeding.

    For example of 2, consider:

    #include 
    #include 
    #include 
    
    int main(int argc, char** argv) {
      int t=time(NULL);
      srand(t);
    
      for(int i=0; i < 10; i++) {
        float r = (float)rand()/(float)(RAND_MAX);
        printf("%f\n", r);
      }
    }
    

    With the result:

    0.460600
    0.310486
    0.339473
    0.519799
    0.258825
    0.072276
    0.749423
    0.552250
    0.665374
    0.939103
    

    It's still a bad RNG but at least the range is better when you allow it to use the internal state instead of giving it another similar seed.

提交回复
热议问题