设为首页 加入收藏

TOP

C++库研究笔记――生成一组随机数
2014-11-23 21:34:30 来源: 作者: 【 】 浏览:1
Tags:研究 笔记 生成 随机

当试图用

srand(time(0))

rand()

生成一组随机数时发现,生成的数字很多都是「一样」的

经过测试:srand(seed); rand() 生成随机数,当seed一样时,生成的随机数相同。

所以上述「一样」的问题应该出在time(0)

所以最后采用的方式是:sleep+ 高精度计时,+srand(gettime_function) +rand()

不过,

[cpp] view plaincopyprint 把gettimeofday换成更高精度可能效果更好

把gettimeofday换成更高精度可能效果更好

代码如下(Linux下)


 include  // for srand  
#include   
#include    // for nanosleep  
#include    // for gettimeofday 

#include  // for srand
#include 
#include    // for nanosleep
#include    // 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 timeva l 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 timeva l 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 timeva l 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 timeva l cur;
    gettimeofday(&cur, 0);
    srand(cur.tv_usec);
    return rand()%(max+1);
}

结果:

\
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇hdu 1392凸包周长 下一篇学习总结---拓扑排序

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·如何从内核协议栈到 (2025-12-27 03:19:09)
·什么是网络协议?有哪 (2025-12-27 03:19:06)
·TCP/ IP协议有哪些 (2025-12-27 03:19:03)
·怎样用 Python 写一 (2025-12-27 02:49:19)
·如何学习python数据 (2025-12-27 02:49:16)