一様乱数と正規乱数

C++11からboostなくてもよくなったんで、使い方メモっておく。正規分布に設定するパラメーターは平均と"標準偏差"であって、"分散"ではない点に注意。
あと、擬似乱数生成器をあえて値渡ししてるんだけど、内部で保有しているとおもわれる乱数の状態もコピーするっぽく、乱数は"seedで指定した値のはじめから"ではなく、"続きから"出てくる点も注意する。

#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>

template<class T_>
void show_histgram(T_ & dist, std::mt19937 engine)
{
	//ヒストグラム生成
	std::cout << "======= show histgram =========" << std::endl;
	std::map<int, int> hist;
	for (int n = 0; n < 10000; ++n){ ++hist[std::round(dist(engine))]; }
	for (auto p : hist)
	{
		std::cout << std::fixed << std::setprecision(1) << std::setw(2)
			<< p.first << ' ' << std::string(p.second / 200, '*') << std::endl;
	}
}
template<class T_>
void show_value(T_ & dist, std::mt19937 engine, int n)
{
	//値表示
	std::cout << "======= show values =========" << std::endl;
	for(int i = 0; i < n; ++i){ std::cout << dist(engine) << std::endl; }
}
int main()
{
	//シードを100に固定したメルセンヌ・ツイスター乱数生成器
	std::mt19937 engine(100);

	// 平均0, "標準偏差"2の正規分布 & 一様分布
	std::normal_distribution<> normal(0, 2);
	std::uniform_real_distribution<> unif(-3.0, 3.0);
	//ヒストグラム表示
	show_histgram(normal, engine);
	show_histgram(unif, engine);
	//値表示
	show_value(normal, engine, 5);
	show_value(normal, engine, 5);
}

実行結果

======= show histgram =========
-8
-7
-6
-5
-4 *
-3 ***
-2 ******
-1 ********
 0 **********
 1 ********
 2 *****
 3 ***
 4 *
 5
 6
 7
 8
======= show histgram =========
-3 ****
-2 ********
-1 ********
 0 ********
 1 ********
 2 *******
 3 ****
======= show values =========
1.0
4.0
-3.2
-1.3
-5.1
======= show values =========
1.8
1.0
4.0
-3.2
-1.3