mardi 21 février 2017

C rand() is not random even when seeded

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

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

int main(int argc, char** argv) {
  srand(time(NULL));

  float r = (float)rand()/(float)(RAND_MAX);
  printf("%f", r);
}

I compile the above piece of code using

gcc randd.c

Then running it 5 times manually and the numbers don't seem random:

0.197940

0.197947

0.197955

0.197979

0.197994

Running this on another machine and it performs as it should. It has to do something with the time as in the morning it kept returning around 0.19 and now it's around 0.45. Any ideas as to what could be causing this?




Aucun commentaire:

Enregistrer un commentaire