正态漫衍(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;
}
输出:
0 : 3*** 1 : 8******** 2 : 20******************** 3 : 38************************************** 4 : 58********************************************************** 5 : 42****************************************** 6 : 23*********************** 7 : 7******* 8 : 1* sum = 200
作者:csdn博客 Spike_King
