使用乘加進位法生成隨機數的 C++ 程式


乘加進位法是馬薩里亞和扎曼 (1991) 提出的加法進位生成器的一種變體。這種方法的主要優點是它使用簡單的計算機整數運算,可以非常快速地生成具有巨大週期的隨機數序列,範圍從大約 260 到 22000000。

在 MWC 基礎中,b 選擇為等於計算機字長,乘數 a 和延遲 r 決定模數 p = abr−1。在此,a 選擇為模數是質數,並且乘數具有長週期。

演算法

Begin
   Declare maximum _sequence _elements, b, r, c[maximum _sequence _elements],
   x[maximum _sequence _elements]
   Read the variables maximum _sequence _elements, b, r
   m = rand() mod b
   c[0] = rand() mod m
   x[0] = rand() mod b
   For I = 1 to maximum_sequence_element, do
      x[i] = (m * x[i - r] + c[i - 1]) mod b
      c[i] = (m * x[i - r] + c[i - 1]) / b
      print the sequence.
   Done.
End.

示例程式碼

#include <iostream>
using namespace std;
int main(int argc, char **argv) {
   int max_Seq_Elements = 7;
   int b = 300;
   int m = rand() % b;
   int r = 1;
   int c[max_Seq_Elements];
   int x[max_Seq_Elements];
   c[0] = rand() % m;
   x[0] = rand() % b;
   cout << "The random number sequence is: " << x[0];
   for (int i = 1; i < max_Seq_Elements; i++) {
      x[i] = (m * x[i - r] + c[i - 1]) % b;
      c[i] = (m * x[i - r] + c[i - 1]) / b;
      cout << " " << x[i];
   }
   cout << "...";
}

輸出

The random number sequence is: 177 173 226 221 56 157 84...

更新於: 30-Jul-2019

232 瀏覽量

開啟您的 職業生涯

完成該教程獲得認證

開始
廣告