<random>

<random>

std::bernoulli_distribution

class bernoulli_distribution;
伯努利分佈 (Bernoulli distribution)
根據伯努利分佈生成隨機數的分佈。bool伯努利分佈描述如下機率質量函式



其中“真”的機率為truep,而“假”的機率為false(1-p)

這代表了最簡單的分佈函式之一:拋硬幣的分佈符合伯努利分佈,其正面朝上的機率約為0.5.

分佈引數 p構造時設定。

要生成遵循此分佈的隨機值,請呼叫其成員函式 operator()

成員型別

以下別名是伯努利分佈 (bernoulli_distribution):

成員型別定義說明
result_typebool生成的the type of the results
param_type未指定 (not specified)成員 param 返回的型別。

成員函式


分佈引數


非成員函式


示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// bernoulli_distribution
#include <iostream>
#include <random>

int main()
{
  const int nrolls=10000;

  std::default_random_engine generator;
  std::bernoulli_distribution distribution(0.5);

  int count=0;  // count number of trues

  for (int i=0; i<nrolls; ++i) if (distribution(generator)) ++count;

  std::cout << "bernoulli_distribution (0.5) x 10000:" << std::endl;
  std::cout << "true:  " << count << std::endl;
  std::cout << "false: " << nrolls-count << std::endl;

  return 0;
}

可能的輸出
bernoulli_distribution (0.5) x 10000:
true:  4994
false: 5006


另見