随机数是一个有趣的话题,有时候我们需要随机数来生成密钥或者模拟一些数据来做测试。软件产生的随机数大部分是伪随机数,C++ 标准库为我们提供了若干伪随机数操作的方法和类。
🐭 C 中的随机数
C 语言中的伪随机数比较简单,产生的随机数范围和质量都不够好,在比较严肃的场合不推荐使用。
#include <iostream>#include <random>int main() {// use current time point as seed for random generatorstd::srand(std::time(nullptr));int rv = std::rand();std::cout << "Random value in [0, " << RAND_MAX << "]: " << rv << '\n';// Random value in [0, 2147483647]: 1556741592// roll a six sided die 16 timesfor (int x = 0, n = 0; n != 16; ++n) {do {// 1 + rand()%6 is biasedx = 1 + std::rand() / ((RAND_MAX + 1u) / 6);} while (x > 6);std::cout << x << ' ';// 4 5 2 4 3 2 5 1 2 6 4 6 5 3 6 2}std::cout << '\n';return 0;}
🐂 C++ 中的随机数
C++ 中的随机数分为三个部分:
- 随机数种子 S
- 均匀随机数生成器 G
- 随机数分布 D
均匀随机数生成器 G 利用随机数种子 S 生成均匀分布的整数系列,随机数分布 D 负责把 G 产生的随机数转换为符合指定的统计分布类型,对于随机数的使用来说 G 比 D 重要。
#include <iomanip>#include <iostream>#include <map>#include <random>#include <string>int main() {// the true random number generator rd using hardware entropystd::random_device rd{};// a special random engine use rd() return value as seedunsigned int seed = rd();std::mt19937 g{seed};std::cout << "seed = " << seed << '\n';// a normal statistical distribution (mean = 5 and stddev = 2)std::normal_distribution<> d{5, 2};std::map<int, int> hist{};for (int n = 0; n < 10000; ++n) {// d convert the output of g into normal statistical distribution++hist[std::round(d(g))];}for (auto [n, p] : hist) {std::cout << std::setw(2) << n << ' ' << std::string(p / 150, '*') << '\n';}#if 0seed = 3862269836-3-2-101 *2 ****3 *******4 ***********5 *************6 ***********7 ********8 ****9 *101112#endifreturn 0;}
为了方便使用,我们也可以封装自己的随机数生成器 (区间均匀分布随机数生成器),方便生成测试数据。
#include <algorithm>#include <iostream>#include <random>struct RandomNumberBetween {RandomNumberBetween(int low, int high): random_engine_{std::random_device{}()}, distribution_{low, high} {}int operator()() { return distribution_(random_engine_); }private:std::mt19937 random_engine_;std::uniform_int_distribution<int> distribution_;};int main(void) {// generate 16 random numbers between [1, 100]std::vector<int> numbers;std::generate_n(std::back_inserter(numbers), 16, RandomNumberBetween(1, 100));std::copy(numbers.begin(), numbers.end(), std::ostream_iterator<int>(std::cout, " "));std::cout << '\n'; // 37 48 99 20 44 95 24 81 55 35 78 86 82 6 12 44return 0;}
🐯 随机数种子
对于随机数生成器来说种子比较重要,好的种子能产生高质量的随机数,在 C 中我们一般使用当前的时间作为随机数种子。在 C++ 中选择性就比较多了,可以使用单个种子,也可以使用种子系列 (多个种子共同起作用)。
#include <iomanip>#include <iostream>#include <map>#include <random>int main(void) {// a real random enginestd::random_device rd{};// random seed sequencestd::seed_seq seq{rd(), rd(), rd(), rd()};// another random engine use multi seedstd::mt19937 g{seq};// normal random distributionstd::normal_distribution<> d{5, 2};std::map<int, int> hist{};for (int n = 0; n < 10000; ++n) {// generate random numbers d(g())++hist[std::round(d(g))];}for (auto [n, p] : hist) {std::cout << std::setw(2) << n << ' ' << std::string(p / 150, '*') << '\n';}#if 0-2-101 **2 ****3 ********4 ***********5 *************6 ***********7 *******8 ****9 *101112#endifreturn 0;}
