命名空间
变体
操作

std::binomial_distribution

来自 cppreference.cn
< cpp‎ | numeric‎ | random
 
 
 
 
 
定义于头文件 <random>
template< class IntType = int >
class binomial_distribution;
(C++11 起)

产生随机非负整数值 i,根据离散概率函数分布

P(i|t,p) =

t
i


· pi
· (1 − p)t−i

获得的值是在 t 次是/否实验中成功的次数,每次实验成功的概率为 p

std::binomial_distribution 满足 RandomNumberDistribution

内容

[编辑] 模板参数

IntType - 生成器产生的结果类型。如果这不是 shortintlonglong longunsigned shortunsigned intunsigned longunsigned long long 之一,则效果未定义。

[编辑] 成员类型

成员类型 定义
result_type (C++11) IntType
param_type (C++11) 参数集类型,见 RandomNumberDistribution

[编辑] 成员函数

构造新的分布
(公有成员函数) [编辑]
(C++11)
重置分布的内部状态
(公有成员函数) [编辑]
生成
生成分布中的下一个随机数
(公有成员函数) [编辑]
特性
(C++11)
返回分布参数
(公有成员函数) [编辑]
(C++11)
获取或设置分布参数对象
(公有成员函数) [编辑]
(C++11)
返回可能生成的最小值
(公有成员函数) [编辑]
(C++11)
返回可能生成的最大值
(公有成员函数) [编辑]

[编辑] 非成员函数

(C++11)(C++11)(C++20 中移除)
比较两个分布对象
(函数) [编辑]
对伪随机数分布执行流输入和输出
(函数模板) [编辑]

[编辑] 示例

二项分布的图示,每次试验成功的概率恰好为 0.5,说明了与帕斯卡三角形的关系(在此情况下,4 次试验中 0 次、1 次、2 次、3 次或全部 4 次成功的概率为 1:4:6:4:1)。

#include <iomanip>
#include <iostream>
#include <map>
#include <random>
#include <string>
 
int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    // perform 4 trials, each succeeds 1 in 2 times
    std::binomial_distribution<> d(4, 0.5);
 
    std::map<int, int> hist;
    for (int n = 0; n != 10000; ++n)
        ++hist[d(gen)];
 
    for (auto const& [x, y] : hist)
        std::cout << x << ' ' << std::string(y / 100, '*') << '\n';
}

可能的输出

0 ******
1 ************************
2 *************************************
3 *************************
4 ******

[编辑] 外部链接

Weisstein, Eric W. "二项分布。" 来自 MathWorld — Wolfram Web 资源。