Поделиться через


Класс binomial_distribution

Формирует биномиальное распределение.

Синтаксис

template<class IntType = int>
class binomial_distribution
   {
public:
   // types
   typedef IntType result_type;
   struct param_type;

   // constructors and reset functions
   explicit binomial_distribution(result_type t = 1, double p = 0.5);
   explicit binomial_distribution(const param_type& parm);
   void reset();

   // generating functions
   template <class URNG>
   result_type operator()(URNG& gen);
   template <class URNG>
   result_type operator()(URNG& gen, const param_type& parm);

   // property functions
   result_type t() const;
   double p() const;
   param_type param() const;
   void param(const param_type& parm);
   result_type min() const;
   result_type max() const;
   };

Параметры

IntType
По умолчанию целочисленный тип результата имеет тип int. Сведения о возможных типах см <. в случайном> порядке.

URNG
Модуль генератора случайных чисел. Сведения о возможных типах см <. в случайном> порядке.

Замечания

Шаблон класса описывает распределение, которое создает значения заданного пользователем целочисленного типа или тип int , если он не указан, распределенный в соответствии с дискретной функцией вероятности Binomial Distribution. В следующей таблице представлены ссылки на статьи об отдельных членах.

binomial_distribution
param_type

Элементы t() свойства и p() возвращают значения параметров распределения в данный момент t и p соответственно.

Член свойства param() устанавливает или возвращает хранимый пакет параметров распределения param_type.

Функции-члены min() и max() возвращают наименьший и наибольший из возможных результатов соответственно.

Функция-член reset() удаляет любые кэшированные значения, чтобы результат следующего вызова operator() не зависел от любых значений, полученных от механизма перед вызовом.

Функции-члены operator() возвращают следующее значение, созданное механизмом РГСЧ, из текущего или указанного пакета параметров.

Дополнительные сведения о классах распространения и их членах см. в случайном порядке>.<

Дополнительные сведения о дискретной функции вероятности биномиального распределения см. в статье Биномиальное распределение на веб-сайте Wolfram MathWorld.

Пример

// compile with: /EHsc /W4
#include <random>
#include <iostream>
#include <iomanip>
#include <string>
#include <map>

void test(const int t, const double p, const int& s) {

    // uncomment to use a non-deterministic seed
    //    std::random_device rd;
    //    std::mt19937 gen(rd());
    std::mt19937 gen(1729);

    std::binomial_distribution<> distr(t, p);

    std::cout << std::endl;
    std::cout << "p == " << distr.p() << std::endl;
    std::cout << "t == " << distr.t() << std::endl;

    // generate the distribution as a histogram
    std::map<int, int> histogram;
    for (int i = 0; i < s; ++i) {
        ++histogram[distr(gen)];
    }

    // print results
    std::cout << "Histogram for " << s << " samples:" << std::endl;
    for (const auto& elem : histogram) {
        std::cout << std::setw(5) << elem.first << ' ' << std::string(elem.second, ':') << std::endl;
    }
    std::cout << std::endl;
}

int main()
{
    int    t_dist = 1;
    double p_dist = 0.5;
    int    samples = 100;

    std::cout << "Use CTRL-Z to bypass data entry and run using default values." << std::endl;
    std::cout << "Enter an integer value for t distribution (where 0 <= t): ";
    std::cin >> t_dist;
    std::cout << "Enter a double value for p distribution (where 0.0 <= p <= 1.0): ";
    std::cin >> p_dist;
    std::cout << "Enter an integer value for a sample count: ";
    std::cin >> samples;

    test(t_dist, p_dist, samples);
}

Первый запуск:

Use CTRL-Z to bypass data entry and run using default values.
Enter an integer value for t distribution (where 0 <= t): 22
Enter a double value for p distribution (where 0.0 <= p <= 1.0): .25
Enter an integer value for a sample count: 100

p == 0.25
t == 22
Histogram for 100 samples:
    1 :
    2 ::
    3 :::::::::::::
    4 ::::::::::::::
    5 :::::::::::::::::::::::::
    6 ::::::::::::::::::
    7 :::::::::::::
    8 ::::::
    9 ::::::
    11 :
    12 :

Второй запуск:

Use CTRL-Z to bypass data entry and run using default values.
Enter an integer value for t distribution (where 0 <= t): 22
Enter a double value for p distribution (where 0.0 <= p <= 1.0): .5
Enter an integer value for a sample count: 100

p == 0.5
t == 22
Histogram for 100 samples:
    6 :
    7 ::
    8 :::::::::
    9 ::::::::::
    10 ::::::::::::::::
    11 :::::::::::::::::::
    12 :::::::::::
    13 :::::::::::::
    14 :::::::::::::::
    15 ::
    16 ::

Третий запуск:

Use CTRL-Z to bypass data entry and run using default values.
Enter an integer value for t distribution (where 0 <= t): 22
Enter a double value for p distribution (where 0.0 <= p <= 1.0): .75
Enter an integer value for a sample count: 100

p == 0.75
t == 22
Histogram for 100 samples:
    13 ::::
    14 :::::::::::
    15 :::::::::::::::
    16 :::::::::::::::::::::
    17 ::::::::::::::
    18 :::::::::::::::::
    19 :::::::::::
    20 ::::::
    21 :

Требования

Заголовок:<random>

Пространство имен: std

binomial_distribution::binomial_distribution

Формирует распределение.

explicit binomial_distribution(result_type t = 1, double p = 0.5);
explicit binomial_distribution(const param_type& parm);

Параметры

с
Параметр распределения t.

p
Параметр распределения p.

parm
Структура param_type, используемая для формирования распределения.

Замечания

Предварительные условия: 0 ≤ t и 0.0 ≤ p ≤ 1.0

Первый конструктор создает объект, сохраненный значение p которого содержит значение p и хранящееся t значение содержит значение t.

Второй конструктор создает объект, хранимые параметры которого инициализируются из parm. Вы можете получить и задать текущие параметры существующего распределения, вызвав функцию-член param().

binomial_distribution::param_type

Сохраняет все параметры распределения.

struct param_type {
   typedef binomial_distribution<result_type> distribution_type;
   param_type(result_type t = 1, double p = 0.5);
   result_type t() const;
   double p() const;
   .....
   bool operator==(const param_type& right) const;
   bool operator!=(const param_type& right) const;
   };

Параметры

с
Параметр распределения t.

p
Параметр распределения p.

right
Объект param_type, который требуется сравнить с данным объектом.

Замечания

Предварительные условия: 0 ≤ t и 0.0 ≤ p ≤ 1.0

Эту структуру можно передать конструктору класса распределения во время создания экземпляра, функции-члену param() для установки хранимых параметров существующего распределения и operator() для использования вместо хранимых параметров.

См. также

<random>