C++随机数生成器的手动实现与泊松分布

课上一个半小时写出来的,望各位不吝赐教~

随机数的生成器老师给定了一个生成实数的函数,根据这个模板自己实现了一个随机生成范围内整数的函数。之后实现了一个泊松分布的随机数生成器,给定均值和数据个数,生成指定个数的泊松分布随机数。

下面上代码~

Random.h

#ifndef RANDOM_H_INCLUDED
#define RANDOM_H_INCLUDED

#include 
#include 
#include 
#include 

using namespace std;

class Random {

public:
    Random(bool pseudo = true);
    double random_real();
    int random_integer(int low, int high);
    int poisson(double mean);

private:
    int reseed(); //  Re-randomize the seed.
    int seed,multiplier,add_on;   //  constants for use in arithmetic operations

};

#endif // RANDOM_H_INCLUDED

Random.cpp

#include "Random.h"

Random::Random(bool pseudo)
/*Post: The values of seed, add_on, and multiplier are
        initialized.  The seed is initialized randomly only if pseudo == false.
*/
{
    if (pseudo)
        seed = 1;
    else seed = time(NULL) % INT_MAX;
    multiplier = 2743;  // 斜率
    add_on = 5923;  // 位移
}

int Random::reseed()
//Post: The seed is replaced by a pseudorandom successor.
{
    seed = seed * multiplier + add_on;
    return seed;
}

double Random::random_real()
/*Post: A random real number between 0 and 1 is returned.*/
{
    double max = INT_MAX + 1.0;  //INT_MAX = (2)31 -1
    double temp = reseed();
    if (temp < 0) temp = temp + max;
    return temp / max;
}

int Random::random_integer(int low, int high)  // 这个函数在泊松分布中没有用到
{
    double max = INT_MAX + 1.0;  //INT_MAX = (2)31 -1
    double temp = reseed();
    if (temp < 0) temp = temp + max;
    return (int)(temp / (max / (high - low + 1.0) + low));  // 返回整数,且有规定范围
}

int Random::poisson(double mean)  // 泊松分布的实现
{
    double x = -1;
    double u;
    double log1, log2;
    log1 = 0;
    log2 = -mean;
    do {
        u = random_real();
        log1 += log(u);
        x++;
    } while (log1 >= log2);
    return x;
}

main.cpp

#include "Random.h"

int main(void)
{
    Random r(true);
    double mean;  // 输入的均值
    int num;  // 输入的个数
    double mean_total;  // 最后计算的均值
    double sum = 0.0f;
    cout << "请输入概率均值:" << endl;
    cin >> mean;
    cout << "请输入产生随机整数的个数:" << endl;
    cin >> num;
    for (int i = 0; i < num; i++) {
        int tmp = r.poisson(mean);
        cout << tmp << " ";
        sum += (double)tmp;
    }
    cout << endl;
    mean_total = sum / (double)num;
    cout << "随机整数序列的平均值是:" << mean_total << endl << endl;
    cout << "在泊松分布中没有体现ramdom_integer函数的效果,所以以下部分是对这个函数进行测试" << endl << endl;
    cout << "请输入两个整数a, b, a < b:" << endl;
    int a, b;
    cin >> a >> b;
    cout << "生成100个随机整数:" << endl;
    for (int i = 0; i < 100; i++) {
        cout << r.random_integer(a, b) << " ";
    }
    cout << endl;
    system("pause");
    return 0;
}

 

你可能感兴趣的:(C++)