c – 创建具有平均和标准偏差的高斯随机发生器

前端之家收集整理的这篇文章主要介绍了c – 创建具有平均和标准偏差的高斯随机发生器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试创建一个一维数组,并使用一个随机生成器(高斯生成器,生成70的均值和标准差为10的随机数),以填充至少100个数字在0和100之间的数组.

我怎么会这样做在C?

解决方法

在C 11中,这是相对简单的使用 random headerstd::normal_distribution( live example):
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <string>
  4. #include <map>
  5. #include <random>
  6.  
  7. int main()
  8. {
  9. std::random_device rd;
  10.  
  11. std::mt19937 e2(rd());
  12.  
  13. std::normal_distribution<> dist(70,10);
  14.  
  15. std::map<int,int> hist;
  16. for (int n = 0; n < 100000; ++n) {
  17. ++hist[std::round(dist(e2))];
  18. }
  19.  
  20. for (auto p : hist) {
  21. std::cout << std::fixed << std::setprecision(1) << std::setw(2)
  22. << p.first << ' ' << std::string(p.second/200,'*') << '\n';
  23. }
  24. }

如果C 11不是boost,也提供了一个库(live example):

  1. #include <iostream>
  2. #include <iomanip>
  3. #include <string>
  4. #include <map>
  5. #include <random>
  6. #include <boost/random.hpp>
  7. #include <boost/random/normal_distribution.hpp>
  8.  
  9. int main()
  10. {
  11.  
  12. boost::mt19937 *rng = new boost::mt19937();
  13. rng->seed(time(NULL));
  14.  
  15. boost::normal_distribution<> distribution(70,10);
  16. boost::variate_generator< boost::mt19937,boost::normal_distribution<> > dist(*rng,distribution);
  17.  
  18. std::map<int,int> hist;
  19. for (int n = 0; n < 100000; ++n) {
  20. ++hist[std::round(dist())];
  21. }
  22.  
  23. for (auto p : hist) {
  24. std::cout << std::fixed << std::setprecision(1) << std::setw(2)
  25. << p.first << ' ' << std::string(p.second/200,'*') << '\n';
  26. }
  27. }

如果由于某些原因,这些选项都不可能,那么您可以滚动自己的Box-Muller transform,链接中提供的代码看起来很合理.

猜你在找的C&C++相关文章