正態分布(norm distribution), 做為一種重要的分布規律, 有廣泛的用途;
注意正態分布包含兩個參數, 均值(mean) 和標准差(standard deviation);
隨機庫(#include <random>), 包含正態分布對象, norm_distribution<>, 可以用於生成正態分布;
代碼如下:
#include <iostream>
#include <vector>
#include <string>
#include <random>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
std::default_random_engine e; //引擎
std::normal_distribution<double> n(4, 1.5); //均值, 方差
std::vector<unsigned> vals(9);
for(std::size_t i=0; i != 200; ++i) {
unsigned v = std::lround(n(e)); //取整-最近的整數
if (v < vals.size())
++vals[v];
}
for (std::size_t j=0; j != vals.size(); ++j)
std::cout << j << " : " << vals[j] << std::string(vals[j], '*') << std::endl;
int sum = std::accumulate(vals.begin(), vals.end(), 0);
std::cout << "sum = " << sum << std::endl;
return 0;
}