CSDN博客

img NetSniffer

随机数生成类C++源码

发表于2004/10/14 10:33:00  1746人阅读

#include <iostream>
#include <time.h>

using namespace std;

class randomNumber
{
 public:
  randomNumber(long s = 0);
  long random();
  long random(long n);
  double frandom();

 private:
  static const long A;
        static const long M;
        static const long Q;
        static const long R;

        long seed;
};

const long randomNumber::A = 48271;
const long randomNumber::M = 2147483647;
const long randomNumber::Q = M / A;
const long randomNumber::R = M % A;

randomNumber::randomNumber(long s)
{
 if (s < 0)
        s = 0;
 
 if (s == 0)
 {
  long t_time = time(NULL);
        t_time *= t_time;
        if (t_time > 0)
            s = t_time ^ 0x5EECE66DL;
        else if (t_time < 0)
            s = (t_time & 0x7fffffff) ^ 0x5EECE66DL;
        else
            s = 0x5EECE66DL;
 }
   
 seed = s;
}

long randomNumber::random()
{
    long tmpSeed = A * ( seed % Q ) - R * ( seed / Q );

    if( tmpSeed >= 0 )
        seed = tmpSeed;
    else
        seed = tmpSeed + M;

    return seed;
}

long randomNumber::random(long n)
{
    double fraction = double(random())/double(M);

    return int(fraction * n);
}

double randomNumber::frandom()
{
    return double(random())/double(M);
}

阅读全文
0 0

相关文章推荐

img
取 消
img