随机数是一个有趣的话题,有时候我们需要随机数来生成密钥或者模拟一些数据来做测试。软件产生的随机数大部分是伪随机数,C++ 标准库为我们提供了若干伪随机数操作的方法和类。

🐭 C 中的随机数

C 语言中的伪随机数比较简单,产生的随机数范围和质量都不够好,在比较严肃的场合不推荐使用。

  1. #include <iostream>
  2. #include <random>
  3. int main() {
  4. // use current time point as seed for random generator
  5. std::srand(std::time(nullptr));
  6. int rv = std::rand();
  7. std::cout << "Random value in [0, " << RAND_MAX << "]: " << rv << '\n';
  8. // Random value in [0, 2147483647]: 1556741592
  9. // roll a six sided die 16 times
  10. for (int x = 0, n = 0; n != 16; ++n) {
  11. do {
  12. // 1 + rand()%6 is biased
  13. x = 1 + std::rand() / ((RAND_MAX + 1u) / 6);
  14. } while (x > 6);
  15. std::cout << x << ' ';
  16. // 4 5 2 4 3 2 5 1 2 6 4 6 5 3 6 2
  17. }
  18. std::cout << '\n';
  19. return 0;
  20. }

🐂 C++ 中的随机数

C++ 中的随机数分为三个部分:

  1. 随机数种子 S
  2. 均匀随机数生成器 G
  3. 随机数分布 D

均匀随机数生成器 G 利用随机数种子 S 生成均匀分布的整数系列,随机数分布 D 负责把 G 产生的随机数转换为符合指定的统计分布类型,对于随机数的使用来说 G 比 D 重要。

  1. #include <iomanip>
  2. #include <iostream>
  3. #include <map>
  4. #include <random>
  5. #include <string>
  6. int main() {
  7. // the true random number generator rd using hardware entropy
  8. std::random_device rd{};
  9. // a special random engine use rd() return value as seed
  10. unsigned int seed = rd();
  11. std::mt19937 g{seed};
  12. std::cout << "seed = " << seed << '\n';
  13. // a normal statistical distribution (mean = 5 and stddev = 2)
  14. std::normal_distribution<> d{5, 2};
  15. std::map<int, int> hist{};
  16. for (int n = 0; n < 10000; ++n) {
  17. // d convert the output of g into normal statistical distribution
  18. ++hist[std::round(d(g))];
  19. }
  20. for (auto [n, p] : hist) {
  21. std::cout << std::setw(2) << n << ' ' << std::string(p / 150, '*') << '\n';
  22. }
  23. #if 0
  24. seed = 3862269836
  25. -3
  26. -2
  27. -1
  28. 0
  29. 1 *
  30. 2 ****
  31. 3 *******
  32. 4 ***********
  33. 5 *************
  34. 6 ***********
  35. 7 ********
  36. 8 ****
  37. 9 *
  38. 10
  39. 11
  40. 12
  41. #endif
  42. return 0;
  43. }

为了方便使用,我们也可以封装自己的随机数生成器 (区间均匀分布随机数生成器),方便生成测试数据。

  1. #include <algorithm>
  2. #include <iostream>
  3. #include <random>
  4. struct RandomNumberBetween {
  5. RandomNumberBetween(int low, int high)
  6. : random_engine_{std::random_device{}()}, distribution_{low, high} {}
  7. int operator()() { return distribution_(random_engine_); }
  8. private:
  9. std::mt19937 random_engine_;
  10. std::uniform_int_distribution<int> distribution_;
  11. };
  12. int main(void) {
  13. // generate 16 random numbers between [1, 100]
  14. std::vector<int> numbers;
  15. std::generate_n(std::back_inserter(numbers), 16, RandomNumberBetween(1, 100));
  16. std::copy(numbers.begin(), numbers.end(), std::ostream_iterator<int>(std::cout, " "));
  17. std::cout << '\n'; // 37 48 99 20 44 95 24 81 55 35 78 86 82 6 12 44
  18. return 0;
  19. }

🐯 随机数种子

对于随机数生成器来说种子比较重要,好的种子能产生高质量的随机数,在 C 中我们一般使用当前的时间作为随机数种子。在 C++ 中选择性就比较多了,可以使用单个种子,也可以使用种子系列 (多个种子共同起作用)。

  1. #include <iomanip>
  2. #include <iostream>
  3. #include <map>
  4. #include <random>
  5. int main(void) {
  6. // a real random engine
  7. std::random_device rd{};
  8. // random seed sequence
  9. std::seed_seq seq{rd(), rd(), rd(), rd()};
  10. // another random engine use multi seed
  11. std::mt19937 g{seq};
  12. // normal random distribution
  13. std::normal_distribution<> d{5, 2};
  14. std::map<int, int> hist{};
  15. for (int n = 0; n < 10000; ++n) {
  16. // generate random numbers d(g())
  17. ++hist[std::round(d(g))];
  18. }
  19. for (auto [n, p] : hist) {
  20. std::cout << std::setw(2) << n << ' ' << std::string(p / 150, '*') << '\n';
  21. }
  22. #if 0
  23. -2
  24. -1
  25. 0
  26. 1 **
  27. 2 ****
  28. 3 ********
  29. 4 ***********
  30. 5 *************
  31. 6 ***********
  32. 7 *******
  33. 8 ****
  34. 9 *
  35. 10
  36. 11
  37. 12
  38. #endif
  39. return 0;
  40. }