C++で「XorShift乱数生成アルゴリズム」を書いてみた

naohiro19
記事: 256
登録日時: 14年前
住所: 愛知県

C++で「XorShift乱数生成アルゴリズム」を書いてみた

投稿記事 by naohiro19 » 9年前

C++で「XorShift」乱数生成アルゴリズム」を書いてみました。

CODE:

//XorShift.h
#pragma once

class XorShift {
	unsigned int x, y, z, w;
public:
	XorShift(unsigned int seed = 88675123U);
	unsigned int Rand();
	unsigned int RandRange(int min, int max);

};

CODE:

//XorShift.cpp
#include "XorShift.h"

//XorShiftのコンストラクタ
XorShift::XorShift(unsigned int seed) : w(seed) {
	x = 123456789U;
	y = 362436069U;
	z = 521288629U;
}

//0~2^32-1の範囲の乱数を生成
unsigned int XorShift::Rand() {
	unsigned int t = x ^ (x > 19)) ^ (t ^ (t >> 8));
	return w;
}

//min~maxの範囲の乱数を生成
unsigned int XorShift::RandRange(int min, int max) {
	unsigned int value = Rand();
	return min + value % (max - min);
}
以下はテストプログラムです。

CODE:

#include 
#include 
#include "XorShift.h"

using namespace std;

int main(int argc, const char * argv []) {
	
	XorShift a(static_cast(time(0)));

	for (int i = 0; i < 10; i++) {
		cout << a.RandRange(1, 6) << endl;
	}
	
	return 0;
}
最後に編集したユーザー naohiro19 on 2016年5月02日(月) 15:43 [ 編集 1 回目 ]

コメントはまだありません。