问:如何从先验未知的范围中生成(许多)均匀分布的整数?在性能方面,什么是首选方法(生成数百万个数字)?
背景:在我的应用程序中,我必须在许多地方生成许多伪随机数。我使用单例模式来维护应用程序运行的可重现性。在我的情况下,分布总是均匀的,但问题在于有太多可能的范围无法在C++11样式中预先制作分布对象。
我尝试过的方法:这有两个明显的解决方案,第一个是拥有一次性分布对象,第二个是使用取模将随机数从最广泛的范围转换为所需的范围。但我对这些是否是最佳解决方案表示怀疑 :)
#include <random>
#include <iostream>
#include "limits.h"
using namespace std;
mt19937 mt;
uniform_int_distribution<int> * fixedDist;
uniform_int_distribution<int> * variableDist;
// this version creates and delete dist after just one use
int getIntFromRange1(int from, int to){
variableDist = new uniform_int_distribution<int>(from,to);
int num = (*variableDist)(mt);
delete variableDist;
return num;
}
// this version contains modulo
int getIntFromRange2(int from, int to){
int num = (*fixedDist)(mt);
int diff = to - from;
num = num % diff;
return num + from;
}
int main(){
mt.seed(123456);
fixedDist= new uniform_int_distribution<int>(0,INT_MAX)
int a = getIntFromRange1(1,10); // 1 and 10 are just for illustration
int b = getIntFromRange2(1,10); // can change freely
cout << "a: " << a << endl; // a: 6
cout << "b: " << b << endl; // b: 9
getchar();
}