C rand () is not random even when sowing

This is most likely a problem with the machine, but I can’t understand what might be wrong.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char** argv) {

  srand(time(NULL));
  int r1 = rand();
  int r2 = rand();
  printf("%d %d\n", r1, r2);
}

I am compiling the above code snippet using

gcc randd.c

Then run it several times manually, and the first numbers seem incredibly similar, while the others seem random:

1025720610 1435057801
1025737417 1717533050
1025754224 2000008299
1025771031 134999901
1025787838 417475150

This first challenge rand()seems to be highly time-related and increases dramatically over time. Any ideas as to why this is happening or how to solve it?

This happens in OSX 10.11.

+4
source share
2 answers
  • rand() , , . RNG , ( ). rand .
  • rand, , - , , rand() -.

, 2, :

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

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);
  }
}

:

0.460600
0.310486
0.339473
0.519799
0.258825
0.072276
0.749423
0.552250
0.665374
0.939103

- RNG, , , , , .

+2

, . , " ". . rand() , , . , rand(), . rand() , , , rand() .

, , - : (a) , srand() , rand() , - IPC; (b) - /dev/urandom; (c) - random.org.

+1

Source: https://habr.com/ru/post/1670480/


All Articles