解决方法
在C 11中,这是相对简单的使用
random header和
std::normal_distribution(
live example):
- #include <iostream>
- #include <iomanip>
- #include <string>
- #include <map>
- #include <random>
- int main()
- {
- std::random_device rd;
- std::mt19937 e2(rd());
- std::normal_distribution<> dist(70,10);
- std::map<int,int> hist;
- for (int n = 0; n < 100000; ++n) {
- ++hist[std::round(dist(e2))];
- }
- for (auto p : hist) {
- std::cout << std::fixed << std::setprecision(1) << std::setw(2)
- << p.first << ' ' << std::string(p.second/200,'*') << '\n';
- }
- }
如果C 11不是boost,也提供了一个库(live example):
- #include <iostream>
- #include <iomanip>
- #include <string>
- #include <map>
- #include <random>
- #include <boost/random.hpp>
- #include <boost/random/normal_distribution.hpp>
- int main()
- {
- boost::mt19937 *rng = new boost::mt19937();
- rng->seed(time(NULL));
- boost::normal_distribution<> distribution(70,10);
- boost::variate_generator< boost::mt19937,boost::normal_distribution<> > dist(*rng,distribution);
- std::map<int,int> hist;
- for (int n = 0; n < 100000; ++n) {
- ++hist[std::round(dist())];
- }
- for (auto p : hist) {
- std::cout << std::fixed << std::setprecision(1) << std::setw(2)
- << p.first << ' ' << std::string(p.second/200,'*') << '\n';
- }
- }
如果由于某些原因,这些选项都不可能,那么您可以滚动自己的Box-Muller transform,链接中提供的代码看起来很合理.