std::geometric_distribution
来自cppreference.com
在标头 <random> 定义 | ||
template<class IntType =int> class geometric_distribution; | (C++11 起) | |
生成随机非负整数值 i,分布按照离散概率函数:
- P(i|p) = p · (1 − p)i
该值表示获得单次成功所需的是/否试验(每次以 p 概率成功)次数。
std::geometric_distribution<>(p) 准确等价于 std::negative_binomial_distribution<>(1, p)。它亦为 std::exponential_distribution 的离散对应版本。
std::geometric_distribution
满足随机数分布(RandomNumberDistribution) 。
目录 |
[编辑]模板形参
IntType | - | 生成器所生成的结果类型。如果它不是 short、int、long、longlong、unsignedshort、unsignedint、unsignedlong 或 unsignedlonglong 之一,那么效果未定义。 |
[编辑]成员类型
成员类型 | 定义 |
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;// 同 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){constchar 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. “几何分布。”来自 MathWorld--A Wolfram Web Resource。 |