问:如何从先验未知范围生成(许多)均匀分布的整数?就性能(数百万生成的数字)而言,首选方式是什么?
上下文:在我的应用程序中,我必须在许多地方生成许多伪随机数。我对生成器使用单例模式来保持应用程序运行的可重复性。在我的情况下,分布总是统一的,但问题是有太多可能的范围来预先制作 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();
}