C++初学者指南-5.标准库(第二部分)–随机数生成

C++初学者指南-5.标准库(第二部分)--随机数生成

文章目录

基本概念

#include <random>

random_engine_type engine {seed};

distribution_type distribution {parameters,...};

auto random_value = distribution(engine);
随机性的来源与分布是解耦的。

  • 随机数是由分布产生的

  • 分布使用均匀随机位引擎作为随机性源
    此设计的优点

  • 没有单个全局状态,可以使用多个独立的随机引擎

  • 新的分发类型可以使用现有引擎

  • 可以更改随机性源,同时保持分布类型 (例如,将确定性引擎更改为使用硬件熵的引擎)

例子

统一随机数

cpp 复制代码
#include <random>
// fixed seed(固定种子)
auto const seed = 123;
// Mersenne Twister random engine(梅森旋转随机引擎):
std::mt19937 urbg {seed};  
// generate random ints ∈ [1,6](生成1-6之间的随机整数)
std::uniform_int_distribution<int> distr1 {1, 6};
auto const value1 = distr1(urbg);
auto const value2 = distr1(urbg);
// generate random floats ∈ [-1.2,6.25)(生成-1.2到6.25之间的随机浮点数)
std::uniform_real_distribution<float> distr2 {-1.2f, 6.25f};
auto const value3 = distr2(urbg);

运行示例代码

布尔值("抛硬币")

cpp 复制代码
#include <random>
auto const seed = 123;
auto urbg = std::mt19937 {seed};  
// unfair coin (40% 'true'):
double const p = 0.4;  
auto flip = std::bernoulli_distribution{p};
if (flip(urbg))  // 40% chance
  cout << "heads\n";
else  // 60% chance
  cout << "tails\n";


运行示例代码

正态分布

cpp 复制代码
#include <random>
auto const seed = 123;
auto urbg = std::mt19937 {seed};  
double const mu = 4.0; 
double const sigma = 0.7; 
auto norm = std::normal_distribution<double>{mu,sigma};
auto value = norm(urbg);


运行示例程序

具有独立概率的整数

cpp 复制代码
#include <random>
auto const seed = std::random_device{}();
auto urbg = std::mt19937{seed};  
std::vector<double> ws {1.0, 1.5, 0.5, 2.0};
std::discrete_distribution<int> distr {begin(ws), end(ws)};
std::vector<int> histo (ws.size(), 0);
int const N = 100000;
for (int k = 0; k < N; ++k) {
  auto const i = distr(urbg);
  ++histo[i];
}
std::cout << "Histogram:\n";
for (auto x : histo) {
  auto const size = int(30 * x/double(N));
  cout << std::string(size,'-') << "o\n";
}


运行示例程序

怎么做

种子引擎

  • 使用一个整数类型的 engine_type::result_type
  • 或使用种子序列
  • 在构造函数中: engine_type { seed }
  • 或者使用成员函数  .seed( seed };
cpp 复制代码
#include <random>
#include <chrono>  // clocks
auto e = std::mt19937{};
// seed engine with a constant
e.seed(123);
// ... or with system clock ticks
auto const ticks = std::chrono::system_clock::now().time_since_epoch().count();
e.seed(ticks);
// ... or with hardware entropy
auto const hes = std::random_device{}();
e.seed(hes);
// ... or with a seed sequence
std::seed_seq s {1,5,3,7,0,9};
e.seed(s);
auto distr = std::uniform_real_distribution{-11.0, 15.3};
cout << distr(e) << '\n';

运行示例代码

使用自定义生成器

Lambda生成器

  • 在 lambda 捕获中初始化引擎和分发
  • 重要:lambda 必须标记为 mutable 因为内部状态 引擎和分配需要随着每次调用而改变
cpp 复制代码
#include <random>
auto const seed = std::random_device{}();
auto coin_flip = [
  // init-capture engine + distribution:
  urbg = std::mt19937{seed},
  distr = std::bernoulli_distribution{0.5}
]() mutable -> bool { return distr(urbg); };
// use generator:
cout << coin_flip() << '\n';
auto roll = [
  urbg = std::mt19937{seed},
  distr = std::uniform_int_distribution<int>{1,6}
]() mutable -> int { return distr(urbg); };
cout << roll() << '\n';

运行示例程序

自定义生成器类

如果需要对参数进行更多控制

cpp 复制代码
#include <random>
class DiceRoll {
  using engine_type = std::mt19937;
  // engine + distribution as members:
  engine_type urbg_;
  std::uniform_int_distribution<int> distr_;
public:
  using seed_type = engine_type::result_type;
  // constructor:
  explicit 
  DiceRoll (int sides, seed_type seed = 0) noexcept: 
    urbg_{seed}, distr_{1,sides} {}
  // allows to re-seed
  void seed (seed_type s) noexcept { urbg_.seed(s); }
  // call operator:
  int operator () () noexcept { return distr_(urbg_); }
};

int main () {
  auto const seed = std::random_device{}();
  DiceRoll roll_d20 {20, seed};
  std::cout << roll_d20() << '\n';
}

运行示例程序

shuffle算法


cppreference

cpp 复制代码
#include <algorithm>
#include <random>
// 32 bit mersenne twister engine
auto const seed = std::random_device{}();
auto reng = std::mt19937{seed};
std::vector<int> v {0,1,2,3,4,5,6,7,8};
shuffle(begin(v)+2, begin(v)+7, reng);  
for (int x : v) { cout << x <<' '; }  // 0 1 ... 7 8

运行示例代码

分布类型概述

通用接口

构造

  • distribution_type distr; // with default params
  • distribution_type distr { parameter_object };
  • distribution_type distr { parameter1, parameter2,... parameterN };
    生成值

auto random_value = distribution_object(engine_object);
常见访问器

  • distr.min() → smallest obtainable value(可获得的最小值)

  • distr.max() → largest obtainable value(可获得的最大值)

  • distr.param() → parameter object(参数对象)

  • distr.reset() : reset internal state(复位内部状态)
    参数对象

  • distribution_type::param_type pars { parameter1, parameter2,... parameterN };

  • distribution_type distr1 { pars };

  • distribution_type distr2 { pars };

  • distribution_type distr3 { distr1.param() };
    分布-特定参数访问器

distr.a() .b()  .m() .n() .s()  .alpha() .beta()  .lambda() .mean() .stddev() ...

均匀分布

采样分布

伯努利分布

正态分布

泊松分布

概览表


引擎类型概述

通用引擎接口


线性同余引擎

std::minstd_rand0 // 1969 by Lewis, Goodman, Miller

std::minstd_rand // 1993 by Park, Miller, Stockmeyer
std::linear_congruential_engine
梅森旋转引擎

std::mt19937 // 32-bit, Matsumoto and Nishimura, 1998

std::mt19937_64 // 64-bit, Matsumoto and Nishimura, 2000
std::mersenne_twister_engine
带进位的减法引擎

std::ranlux24_base

std::ranlux48_base
std::subtract_with_carry_engine
引擎适配器
std::discard_block_engine
std::independent_bits_engine
std::shuffle_order_engine

基于适配器的引擎:

std::ranlux24 // discard_block_engine

std::ranlux48 // discard_block_engine

std::knuth_b // shuffle_order_engine
std::default_random_engine

取决于编译器/平台;通常是线性同余生成器。
非确定性熵源
std::random_device

表示一个非确定性随机数生成器,例如,使用硬件熵源。

如果没有可用的非确定性熵源,标准库的实现可以使用伪随机数引擎作为random_device。

测试设备是否真正是非确定性的:

std::random_device rd;
bool non_deterministic = rd.entropy() >  0;
bool deterministic     = rd.entropy() == 0;
auto distr = std::uniform_real_distribution{-1.0,1.0};
auto num = distr(rd);

注意:一些(较旧的)标准库实现尽管其随机设备是非确定性的,但仍然返回0。

相关内容

Random Generator: Combining Engine + Distribution
Random Number Sequences: Control Reproducibility
cppreference: Pseudo-Random Number Generation
cppreference: std::generate_canonical
What C++ Programmers Need to Know about Header  (Walter E. Brown, 2016)

附上原文链接

如果文章对您有用,请随手点个赞,谢谢!^_^

相关推荐
Watermelon Y1 小时前
【C++】多肽
开发语言·c++
碧海蓝天20221 小时前
C++ 线性表、内存操作、 迭代器,数据与算法分离。
开发语言·数据结构·c++·算法
single5941 小时前
【优选算法】(第十七篇)
java·数据结构·c++·vscode·算法·leetcode
C++忠实粉丝2 小时前
C++IO流
开发语言·c++
朔北之忘 Clancy4 小时前
2021 年 12 月青少年软编等考 C 语言二级真题解析
c语言·开发语言·c++·学习·算法·青少年编程·题解
乱打一通4 小时前
C++里的随机数
开发语言·c++
zty郑桐羽呀4 小时前
[C++] 小游戏 征伐 SLG DNF 0.0.1 版本 zty出品
开发语言·数据结构·c++·算法·开源·zty郑桐羽呀·zty
black_blank4 小时前
机器人跳跃问题
数据结构·算法·机器人
杳戢5 小时前
技术美术百人计划 | 《5.1.3 PBR-基于物理的灯光》笔记
图像处理·人工智能·笔记·算法·计算机视觉·技术美术