命名空间
变体
操作

std::bernoulli_distribution

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

根据离散概率函数生成随机布尔值。 true 的概率为

P(b|p) =

p, 如果 btrue
1 − p, 如果 bfalse

std::bernoulli_distribution 满足 RandomNumberDistribution

目录

[编辑] 成员类型

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

[编辑] 成员函数

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

[编辑] 非成员函数

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

[编辑] 示例

#include <iomanip>
#include <iostream>
#include <map>
#include <random>
#include <string>
 
int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    // give "true" 1/4 of the time
    // give "false" 3/4 of the time
    std::bernoulli_distribution d(0.25);
 
    std::map<bool, int> hist;
    for (int n = 0; n < 10000; ++n)
        ++hist[d(gen)];
 
    std::cout << std::boolalpha;
    for (auto const& [key, value] : hist)
        std::cout << std::setw(5) << key << ' '
                  << std::string(value / 500, '*') << '\n';
}

可能的输出

false ***************
 true ****

[编辑] 外部链接

Weisstein, Eric W. "伯努利分布。" 来自 MathWorld — Wolfram Web Resource。