随机产生0-1之间实数的方法

#define m 65536L
#define b 1194211693L
#define c 12345L

class RandomNumber
{
private:
    unsigned long d; // d 为当前种子
public:
    RandomNumber(unsigned long s = 0); //默认值0 表示由系统自动产生种子
    unsigned short random(unsigned long n); //产生0: n-1之间的随机整数
    double fRandom(void); // 产生[0,1)之间的随机实数
};
#include "RandomNumber.h"

RandomNumber::RandomNumber(unsigned long s)
{
    if(s == 0) d = time_t(0);
    else d = s;
}

unsigned short RandomNumber::random(unsigned long n)
{
    d = b*d+c;
    return (unsigned short)((d >>16) %n); //把d的高16位映射到0-(n-1)范围内
}

//用函数fRandom产生[0,1)之间的随机实数
double RandomNumber::fRandom(void)
{
    return random(m)/double(m);
}
//测试的demo
int main()
{
    RandomNumber d;
    for(int i = 0;i< 1000;i++ )
    cout << d.fRandom() << "  ";
    return 0;
}

你可能感兴趣的:(算法分析)