1. 程式人生 > >數字訊號產生之均勻分佈的隨機數

數字訊號產生之均勻分佈的隨機數

uniform.h

#pragma once

class uniform
{
private:
 double a, b, generate_num;
 long * seed;
 long s;
 int M, N, i, j;

public:
 uniform()
 {
  M = 1048576;
  N = 2045;
 }
 void generate();
 double random_number(double, double, long *);
};

double uniform::random_number(double a, double b, long * 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);
}

uniform.cpp

//混合同餘法產生50個0到1之間均勻分佈的隨機數
#include <iostream>
#include "uniform.h"
#include <iomanip>

using namespace std;

void main()
{
 uniform solution;
 solution.generate();
}

void uniform::generate()
{
 cout << "輸入區間的下限:";
 cin >> a;
 cout << "輸入區間的上限:";
 cin >> b;
 cout << "輸入隨機數的種子:";
 cin >> s;
 cout << "隨機數生成結果為:" << endl;
 for (i = 0; i < 10; i++)
 {
  for (j = 0; j < 5; j++)
  {
   generate_num = random_number(a, b, &s);
   cout << setw(10) << generate_num;
  }
  cout << endl;
 }
}