口碑好的常州做网站,专业网站建设推荐,php网站出现乱码,广告设计排行榜C初学者指南-5.标准库(第二部分)–随机数生成 文章目录 C初学者指南-5.标准库(第二部分)–随机数生成基本概念例子统一随机数布尔值#xff08;“抛硬币”#xff09;正态分布具有独立概率的整数 怎么做种子引擎使用自定义生成器 shuffle算法分布类型概述通用接口均匀分布采样…C初学者指南-5.标准库(第二部分)–随机数生成 文章目录 C初学者指南-5.标准库(第二部分)–随机数生成基本概念例子统一随机数布尔值“抛硬币”正态分布具有独立概率的整数 怎么做种子引擎使用自定义生成器 shuffle算法分布类型概述通用接口均匀分布采样分布伯努利分布正态分布泊松分布概览表 引擎类型概述通用引擎接口 相关内容 基本概念 #include random random_engine_type engine {seed}; distribution_type distribution {parameters,…}; auto random_value distribution(engine); 随机性的来源与分布是解耦的。 随机数是由分布产生的分布使用均匀随机位引擎作为随机性源 此设计的优点 没有单个全局状态可以使用多个独立的随机引擎新的分发类型可以使用现有引擎可以更改随机性源同时保持分布类型 例如将确定性引擎更改为使用硬件熵的引擎 例子
统一随机数
#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_distributionint 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_distributionfloat distr2 {-1.2f, 6.25f};
auto const value3 distr2(urbg);运行示例代码
布尔值“抛硬币”
#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% chancecout heads\n;
else // 60% chancecout tails\n;运行示例代码
正态分布
#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_distributiondouble{mu,sigma};
auto value norm(urbg);运行示例程序
具有独立概率的整数
#include random
auto const seed std::random_device{}();
auto urbg std::mt19937{seed};
std::vectordouble ws {1.0, 1.5, 0.5, 2.0};
std::discrete_distributionint distr {begin(ws), end(ws)};
std::vectorint 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 }; #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 因为内部状态 引擎和分配需要随着每次调用而改变
#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_distributionint{1,6}
]() mutable - int { return distr(urbg); };
cout roll() \n;运行示例程序
自定义生成器类 如果需要对参数进行更多控制
#include random
class DiceRoll {using engine_type std::mt19937;// engine distribution as members:engine_type urbg_;std::uniform_int_distributionint 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-seedvoid 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
#include algorithm
#include random
// 32 bit mersenne twister engine
auto const seed std::random_device{}();
auto reng std::mt19937{seed};
std::vectorint 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 paramsdistribution_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)
附上原文链接 如果文章对您有用请随手点个赞谢谢^_^