Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created November 22, 2017 05:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/700acea4def3dc468c2c64c7c3bd7f8e to your computer and use it in GitHub Desktop.
Save komasaru/700acea4def3dc468c2c64c7c3bd7f8e to your computer and use it in GitHub Desktop.
C++ source code to compute random number with LGGs algorithm.
/*********************************************
* 線形合同法による一様乱数生成
*********************************************/
#include <iostream> // for cout
#include <math.h> // for pow
#include <stdio.h> // for printf
using namespace std;
/*
* 計算クラス
*/
class Calc
{
// 宣言
static const int a = 1103515245; // 乗数
static const int c = 12345; // 加数
static const unsigned int m = pow(2, 31); // 法
static const int n = 1000; // 発生させる乱数の個数
int r = 12345; // 乱数の種の初期値
int i; // ループインデックス
public:
// 一様乱数生成
void generateRndnum();
};
/*
* 一様乱数生成
*/
void Calc::generateRndnum()
{
// ループしながら漸化式を計算
for (i = 0; i < n; i++) {
r = (a * r + c) % m;
printf("%10d ", r);
// 5つずつ改行
if (i % 5 == 4)
printf("\n");
}
}
/*
* メイン処理
*/
int main()
{
try
{
// 計算クラスインスタンス化
Calc objCalc;
// 一様乱数生成
objCalc.generateRndnum();
}
catch (...) {
cout << "例外発生!" << endl;
return -1;
}
// 正常終了
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment