随机数的生成

来源:互联网 发布:python 聚合搜索 编辑:程序博客网 时间:2024/06/05 17:02

函数一:int randvoid);

srandseed)中指定seed开始,返回一个范围介于[seedRAND_MAX0x7fff))的随机整数。默认情况下使用的是srand(1)

函数二:void srandunsigned seed);

参数seedrand()的随机种子,即用来初始化rand()的起始值。

 

for(int i=0;i<10;i++)

cout<<setw(4)<<rand()%10;

每次输出的都是: 1   7   4   0   9   4   8   8   2   4

 

srand(1);

for(int i=0;i<10;i++)

cout<<setw(4)<<rand()%10;

每次输出的都是: 1   7   4   0   9   4   8   8   2   4

 

srand(5);

for(int i=0;i<10;i++)

cout<<setw(4)<<rand()%10;

每次输出的都是:4   3   5   9   0   0   7   9   2    0

 

换为srand((unsigned)time(NULL))后每次运行输出的都不一样。但是time(0)只能精确到秒,同一秒内time(0)返回的结果是一样的。

 

方案1

#include<cstdlib>

#include<ctime>

#include<iostream>

#include<iomanip>

using namespace std;

 

int main(){

    long begin=time(0);

    srand((unsigned)time(NULL));

    int count=0;

    for(int i=0;i<100000000;i++)

if(rand()%100==99)

    count++;

    long elapse=time(0)-begin;

    cout<<count<<endl;

    cout<<"elapsed time:"<<elapse<<endl;

 

    return 0;

}

 

方案2

不使用C++提供的rand(),而使用自己的线性同余法制造随机数。

const long MUL=16807L;             

const long ADD=0;                   

const long MOD=0x7fffffffL;   

//线性同余法产生无符号随机数

inline unsigned myRand(){

 static long seed=(long)time(NULL);

 seed=(seed*MUL+ADD)%MOD;

 return (unsigned)seed>>17;      //linear congruential method16位随机性比较好,我们只用它的高15,返回值在[0,32767]

}

 

方案3

把线性同余法LCG(linear congruential generator) 的ADD参数改为13849

 

采用g++编译器在我的机子上运行10次:

方案

Count平均值

平均运行时间(秒)

1

997918.1

2.4

2

997840.3

1.5

3

997936.9

1.4

看来方案3表现的很不错,关键上时间上很占优势!

现在又有一个新的产生随机数的算法叫作Mersenne twister,据说是目前最好的RNGPythonRuby都采用它作为默认的随机数生成算法。