數字訊號產生之指數分佈的隨機數
uniform.h
#pragma once
class uniform
{
private:
double a, b, generate_num;
int * seed;
int s, M, N, i, j;
public:
uniform()
{
M = 1048576;
N = 2045;
}
void generate();
double random_number(double, double, int *);
};
double uniform::random_number(double a, double b, int * seed)
{
(*seed) = N * (*seed) + 1;
(*seed) = (*seed) - ((*seed) / M) * M;
generate_num = static_cast<double>((*seed)) / M;
generate_num = a + (b - a) * generate_num;
return (generate_num);
}
exponent.h
#pragma once
#include "uniform.h"
#include <math.h>
class exponent
{
private:
double beta, u, x, generate_num;
int s, i, j;
int *seed;
public:
exponent() {}
void generate();
double random_number(double, int *);
};
double exponent::random_number(double beta, int * seed)
{
uniform unif_num;
u = unif_num.random_number(0.0, 1.0, seed);
x = -beta * log(u);
return (x);
}
exponent.cpp
//產生50個均值為2、方差為4的指數分佈的隨機數
#include <iostream>
#include <iomanip>
#include "exponent.h"
using namespace std;
void main()
{
exponent solution;
solution.generate();
}
void exponent::generate()
{
cout << "輸入指數分佈的均值:";
cin >> beta;
cout << "輸入隨機數的種子:";
cin >> s;
cout << "生成隨機數的結果為:" << endl;
for (i = 0; i < 10; i++)
{
for (j = 0; j < 5; j++)
{
generate_num = random_number(beta, &s);
cout << setw(10) << generate_num;
}
cout << endl;
}
}