當試圖用
srand(time(0))
rand()
生成一組隨機數時發現,生成的數字很多都是「一樣」的
經過測試:srand(seed); rand() 生成隨機數,當seed一樣時,生成的隨機數相同。
所以上述「一樣」的問題應該出在time(0)
所以最後采用的方式是:sleep+ 高精度計時,+srand(gettime_function) +rand()
不過,
[cpp] view plaincopyprint?把gettimeofday換成更高精度可能效果更好
把gettimeofday換成更高精度可能效果更好
代碼如下(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~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);
}
結果: