前言
在 C++11 之前,我们通常用 rand() 来生成随机数。
但 rand() 对一些情况显得难以处理:
- 不同范围的随机数
- 需要随机浮点数
- 需要非均匀分布的随机数
rand() 的使用方法:C 语言 rand 和 srand 使用方法
下文将使用 C++11 定义在头文件 random 中的随机数库,通过一组协作的类来解决这些问题。
- 一个随机数引擎类可以生成 unsigned 随机数序列
- 一个随机数分布类使用一个随机引擎类生成指定类型的、在给定范围内的、服从特定概率分布的随机数
生成等概率随机数
自己在刚开始学习 C++ 的时候,也找过一些 C++ 生成随机数的方法,但大都是在论证是如何生成随机数的,很少有教如何使用的。论证的文章难度大,于是每次看一下就放弃了,只好用 C 语言中的 rand() 再搭配取余使用。
本文只简要介绍如何使用,并给出一些示例。
生成随机整数
uniform_int_distribution:产生均匀分布的整数。
// IntType
// An integer type. Aliased as member type result_type.
// By default, this is int.
template<class IntType = int>
class uniform_int_distribution;
#include <ctime>
#include <iostream>
#include <random>
using namespace std;
int main() {
// 产生 [1, 100] 左闭右闭区间的随机整数
uniform_int_distribution<int> u(1, 100);
default_random_engine e;
// 为随机数引擎设置随机种子, 若不设置每次生成的随机数相同(可以创建时设置)
// 类似 srand() 的用法, 相同的种子生成的随机数相同
// default_random_engine e(time(NULL));
e.seed(time(NULL));
for (size_t i = 0; i < 10; ++i) {
cout << u(e) << " ";
}
cout << endl;
return 0;
}
生成随机浮点数
uniform_real_distribution:产生均匀分布的实数。
// RealType
// A floating-point type. Aliased as member type result_type.
// By default, this is double.
template<class RealType = double>
class uniform_real_distribution;
#include <ctime>
#include <iostream>
#include <random>
using namespace std;
int main() {
// 生成 [-1, 1] 范围随机浮点数
// 模板参数只能是浮点类型(float/double/long double)
uniform_real_distribution<double> u(-1, 1);
default_random_engine e(time(NULL));
for (size_t i = 0; i < 10; ++i) {
cout << u(e) << " ";
}
cout << endl;
return 0;
}
生成非均匀分布随机数
正态分布随机数
template<class RealType = double>
class normal_distribution;
#include <ctime>
#include <iostream>
#include <random>
using namespace std;
int main() {
// 生成符合均值为 10, 标准差为 2 的随机数
normal_distribution<double> u(10, 2);
default_random_engine e(time(NULL));
for (size_t i = 1; i <= 100; ++i) {
printf("%-9.6lf ", u(e));
if (i % 10 == 0) {
cout << endl;
}
}
cout << endl;
return 0;
}
二项分布的布尔值
class bernoulli_distribution;
#include <ctime>
#include <iostream>
#include <random>
using namespace std;
int main() {
// 生成 1 的概率为 0.7
bernoulli_distribution u(0.7);
default_random_engine e(time(NULL));
for (int i = 0; i < 10; ++i) {
cout << u(e) << " ";
}
cout << endl;
return 0;
}