物探论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1236|回复: 0

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

[复制链接]
发表于 2013-8-12 11:28:57 | 显示全部楼层 |阅读模式
当试图用
srand(time(0))
rand()
生成一组随机数时发现,生成的数字很多都是「一样」的
经过测试:srand(seed); rand() 生成随机数,当seed一样时,生成的随机数相同。
所以上述「一样」的问题应该出在time(0)
所以最后采用的方式是:sleep+ 高精度计时,+srand(gettime_function) +rand()
不过,
[cpp] view plaincopy
把gettimeofday换成更高精度可能效果更好  

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

[cpp] 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.jpg
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|物探论坛 ( 鄂ICP备12002012号 微信号:iwutan )

GMT+8, 2024-4-25 07:47 , Processed in 0.092606 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表