dra 发表于 2013-8-12 11:28:57

C++库研究笔记——生成一组随机数

当试图用
srand(time(0))
rand()
生成一组随机数时发现,生成的数字很多都是「一样」的
经过测试:srand(seed); rand() 生成随机数,当seed一样时,生成的随机数相同。
所以上述「一样」的问题应该出在time(0)
所以最后采用的方式是:sleep+ 高精度计时,+srand(gettime_function) +rand()
不过,
view plaincopy
把gettimeofday换成更高精度可能效果更好

代码如下(Linux下)
view plaincopy
#include <stdlib.h> // for srand
#include <limits>
#include <time.h>   // for nanosleep
#include <sys/time.h>   // for gettimeofday
view plaincopy

view plaincopy
/// 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);
}

结果:


页: [1]
查看完整版本: C++库研究笔记——生成一组随机数