C 11从频繁变化的范围生成随机数

前端之家收集整理的这篇文章主要介绍了C 11从频繁变化的范围生成随机数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
问:如何从a-priory未知范围生成(多个)均匀分布的整数?在性能方面(生成的数字的数百万),首选的方式是什么?

上下文:在我的应用程序中,我必须在许多地方生成许多伪随机数.我使用单例模式生成器来保持应用程序运行的可重复性.在我的情况下,分布总是一致的,但问题是在C 11样式中预先制作分发对象的范围太多了.

我尝试过:有两个明显的解决方案,第一个是一次性分配对象,第二个是使用modulo将随机数从最宽的范围转换为所需的范围.但不知何故,我怀疑这些是最好的:)

  1. #include <random>
  2. #include <iostream>
  3. #include "limits.h"
  4. using namespace std;
  5.  
  6. mt19937 mt;
  7. uniform_int_distribution<int> * fixedDist;
  8. uniform_int_distribution<int> * variableDist;
  9.  
  10. // this version creates and delete dist after just one use
  11. int getIntFromRange1(int from,int to){
  12. variableDist = new uniform_int_distribution<int>(from,to);
  13. int num = (*variableDist)(mt);
  14. delete variableDist;
  15. return num;
  16. }
  17.  
  18. // this version contains modulo
  19. int getIntFromRange2(int from,int to){
  20. int num = (*fixedDist)(mt);
  21. int diff = to - from;
  22. num = num % diff;
  23. return num + from;
  24. }
  25.  
  26. int main(){
  27. mt.seed(123456);
  28. fixedDist= new uniform_int_distribution<int>(0,INT_MAX)
  29.  
  30. int a = getIntFromRange1(1,10); // 1 and 10 are just for illustration
  31. int b = getIntFromRange2(1,10); // can change freely
  32.  
  33. cout << "a: " << a << endl; // a: 6
  34. cout << "b: " << b << endl; // b: 9
  35.  
  36. getchar();
  37. }

重复的问题

Vary range of uniform_int_distribution

解决方法

我会做
  1. int getIntFromRange1(int from,int to){
  2. std::uniform_int_distribution<int> dist(from,to);
  3. return dist(mt);
  4. }

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