當前位置:
首頁 > 知識 > C++隨機數生成器的手動實現與泊松分布

C++隨機數生成器的手動實現與泊松分布

隨機數的生成器老師給定了一個生成實數的函數,根據這個模板自己實現了一個隨機生成範圍內整數的函數。之後實現了一個泊松分布的隨機數生成器,給定均值和數據個數,生成指定個數的泊松分布隨機數。

下面上代碼~

Random.h

#ifndef RANDOM_H_INCLUDED

#define RANDOM_H_INCLUDED

#include <iostream>

#include <time.h>

#include <limits.h>

#include <math.h>

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++隨機數生成器的手動實現與泊松分布

打開今日頭條,查看更多圖片

---------------------

作者:LazzyBoi懶惰男孩

原文:https://blog.csdn.net/m0_37717751/article/details/84658447

版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

std::vector::push_back和std::vector::emplace_back的區別
跨域Iframe腳本調用

TAG:程序員小新人學習 |