Random 模块详解
Random 提供统一的随机引擎包装及常用采样与分布函数,便于可复现的随机数据生成。
构造与种子管理
Random():使用基于时钟的默认种子。Random(unsigned seed):用指定种子构造,可实现可复现性。void seed(unsigned s):重新设置引擎种子。unsigned get_seed():(诊断)读取引擎当前状态的一部分(注意这不是原始构造种子)。
基本采样
int randint(int min, int max):闭区间均匀整数。double random(double min=0.0, double max=1.0):实数均匀分布。std::string randstr(int length, const std::string& charset):随机字符串。std::vector<int> randperm(int n):1..n 的随机排列。template<typename T> T choice(const std::vector<T>& container):从容器中随机选择一个元素。
额外分布
double normal(double mean=0,double stddev=1):正态分布。int poisson(double mean):泊松分布。bool bernoulli(double p=0.5):伯努利分布。
加权与不放回采样
template<typename T> T weighted_choice(const std::vector<T>& container, const std::vector<double>& weights):按权重选择。-
权重可为任意非负数,总和需为正。
-
template<typename T> std::vector<T> sample_no_replace(const std::vector<T>& container, size_t k):不放回采样 k 个元素。
水库采样(适合流式/未知长度输入)
template<typename T, typename InputIt> std::vector<T> reservoir_sample(InputIt begin, InputIt end, size_t k)- 从任意可迭代区间中以等概率选出 k 个元素,O(n) 时间、O(k) 空间。
示例代码
using namespace STAR_CPP;
Random rng(42);
// 随机整数/浮点
int a = rng.randint(1, 10);
double x = rng.random(-1.0, 1.0);
// 正态分布
for (int i=0;i<5;++i) std::cout << rng.normal(0,1) << '\n';
// 加权选择
std::vector<std::string> items = {"a","b","c"};
std::vector<double> w = {0.1, 0.2, 0.7};
std::cout << rng.weighted_choice(items, w) << '\n';
// 水库采样示例(从 vector 中选 3 个)
auto v = std::vector<int>{1,2,3,4,5,6,7};
auto s = rng.reservoir_sample<int>(v.begin(), v.end(), 3);
调优建议
- 若需要更高质量或并行 RNG,考虑引入 PCG/Xoroshiro 实现或使用 thread_local 引擎副本。
- 在需要严格重现复杂实验时,记录并固定初始种子。