std::geometric_distribution
来自 cppreference.cn
定义于头文件 <random> |
||
template< class IntType = int > class geometric_distribution; |
(自 C++11 起) | |
产生随机非负整数值 i,根据离散概率函数分布
- P(i|p) = p · (1 − p)i
该值表示在一系列独立的“是/否”试验(每次成功的概率为 p)中,在恰好发生 1 次成功之前,失败的次数。
std::geometric_distribution<>(p) 完全等同于 std::negative_binomial_distribution<>(1, p)。它也是 std::exponential_distribution 的离散对应物。
std::geometric_distribution
满足 RandomNumberDistribution 要求。
目录 |
[编辑] 模板参数
IntType | - | 生成器生成的结果类型。如果这不是 short、int、long、long long、unsigned short、unsigned int、unsigned long 或 unsigned long long 之一,则效果未定义。 |
[编辑] 成员类型
成员类型 | 定义 |
result_type (C++11) |
IntType |
param_type (C++11) |
参数集的类型,参见 RandomNumberDistribution。 |
[编辑] 成员函数
(C++11) |
构造新的分布 (公共成员函数) |
(C++11) |
重置分布的内部状态 (公共成员函数) |
生成 | |
(C++11) |
生成分布中的下一个随机数 (公共成员函数) |
特性 | |
(C++11) |
返回 p 分布参数(试验生成 true 的概率) (公共成员函数) |
(C++11) |
获取或设置分布参数对象 (公共成员函数) |
(C++11) |
返回可能生成的最小值 (公共成员函数) |
(C++11) |
返回可能生成的最大值 (公共成员函数) |
[编辑] 非成员函数
(C++11)(C++11)(在 C++20 中移除) |
比较两个分布对象 (函数) |
(C++11) |
对伪随机数分布执行流输入和输出 (函数模板) |
[编辑] 示例
std::geometric_distribution<>(0.5) 是默认值,表示获得正面所需的抛硬币次数。
运行此代码
#include <iomanip> #include <iostream> #include <map> #include <random> #include <string> int main() { std::random_device rd; std::mt19937 gen(rd()); std::geometric_distribution<> d; // same as // std::negative_binomial_distribution<> d(1, 0.5): std::map<int, int> hist; for (int n = 0; n != 10000; ++n) ++hist[d(gen)]; for (auto [x, y] : hist) { const char c = x < 10 ? x + '0' : x - 10 + 'a'; std::cout << c << ' ' << std::string(y / 100, '*') << '\n'; } }
可能的输出
0 ************************************************* 1 ************************* 2 ************ 3 ****** 4 ** 5 * 6 7 8 9
[编辑] 外部链接
Weisstein, Eric W. "Geometric Distribution." 来自 MathWorld — Wolfram Web 资源。 |