When trying to use
Srand (time (0 ))
Rand ()
When a random number is generated, many of the generated numbers are "same ".
Tested: srand (seed); rand () generates a random number. When seed is the same, the random number is the same.
Therefore, the above "same" problem should be caused by time (0)
So the final method is: sleep + high-precision timing, + srand (gettime_function) + rand ()
However,
[Cpp] view plaincopyprint? Changing gettimeofday to higher precision may result in better results
Changing gettimeofday to higher precision may result in better results
The Code is as follows (in Linux)
include <stdlib.h> // for srand #include <limits> #include <time.h> // for nanosleep #include <sys/time.h> // for gettimeofday #include <stdlib.h> // for srand#include <limits>#include <time.h> // for nanosleep#include <sys/time.h> // for gettimeofday
generate random number between 0~1 inline float randf(void) { struct timespec tim; tim.tv_sec=0; tim.tv_nsec=1e4; nanosleep(&tim, 0); struct timeval cur; gettimeofday(&cur, 0); srand(cur.tv_usec); return rand()/float(RAND_MAX); } inline int randi(int max=1e6) { struct timespec tim; tim.tv_sec=0; tim.tv_nsec=1e4 nanosleep(&tim, 0); struct timeval cur; gettimeofday(&cur, 0); srand(cur.tv_usec); return rand()%(max+1); } /// generate random number between 0~1inline float randf(void){ struct timespec tim; tim.tv_sec=0; tim.tv_nsec=1e4; nanosleep(&tim, 0); struct timeval cur; gettimeofday(&cur, 0); srand(cur.tv_usec); return rand()/float(RAND_MAX);}inline int randi(int max=1e6){ struct timespec tim; tim.tv_sec=0; tim.tv_nsec=1e4 nanosleep(&tim, 0); struct timeval cur; gettimeofday(&cur, 0); srand(cur.tv_usec); return rand()%(max+1);}
Result: