Карта сайта Kansoftware
НОВОСТИУСЛУГИРЕШЕНИЯКОНТАКТЫ
Разработка программного обеспечения

Binomial Coin-Flipping Example

Boost , Math Toolkit 2.5.0 , Binomial Distribution Examples

Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

PrevUpHomeNext

Примером процессаБернуллиявляется подбрасывание монет. Переменная в такой последовательности может быть названа переменной Бернулли.

Этот пример показывает использование биномиального распределения для прогнозирования вероятности голов и хвостов при бросании монеты.

Число правильных ответов (скажем, головок), X, распределено как биномиальная случайная величина с биномиальными параметрами распределения числа испытаний (флипов) n = 10 и вероятностью (успех_фракция) получения головки p = 0,5 (честная монета).

(Наша монета считается справедливой, но мы можем легко изменить параметр success_fraction p с 0,5 на какое-то другое значение, чтобы имитировать нечестную монету, скажем, 0,6 для одной с жевательной резинкой на хвосте, поэтому она с большей вероятностью упадет хвостами вниз и вверх).

Во-первых, нам нужны некоторые включения и использование утверждений, чтобы иметь возможность использовать биномиальное распределение, некоторый вход и выход std и начать:

#include <boost/math/distributions/binomial.hpp>
  using boost::math::binomial;
#include <iostream>
  using std::cout;  using std::endl;  using std::left;
#include <iomanip>
  using std::setw;
int main()
{
  cout << "Using Binomial distribution to predict how many heads and tails." << endl;
  try
  {

См. примечаниес блоком уловао том, почему блок попытки улова всегда является хорошей идеей.

Во-первых, построить биномиальное распределение с параметрами success_fraction 1/2, и сколько переворачиваний.

const double success_fraction = 0.5; // = 50% = 1/2 for a 'fair' coin.
int flips = 10;
binomial flip(flips, success_fraction);
cout.precision(4);

Затем некоторые примеры использования Биномиальных моментов (и повторения параметров).

cout << "From " << flips << " one can expect to get on average "
  << mean(flip) << " heads (or tails)." << endl;
cout << "Mode is " << mode(flip) << endl;
cout << "Standard deviation is " << standard_deviation(flip) << endl;
cout << "So about 2/3 will lie within 1 standard deviation and get between "
  <<  ceil(mean(flip) - standard_deviation(flip))  << " and "
  << floor(mean(flip) + standard_deviation(flip)) << " correct." << endl;
cout << "Skewness is " << skewness(flip) << endl;
// Skewness of binomial distributions is only zero (symmetrical)
// if success_fraction is exactly one half,
// for example, when flipping 'fair' coins.
cout << "Skewness if success_fraction is " << flip.success_fraction()
  << " is " << skewness(flip) << endl << endl; // Expect zero for a 'fair' coin.

Теперь мы показываем множество предсказаний о вероятности голов:

cout << "For " << flip.trials() << " coin flips: " << endl;
cout << "Probability of getting no heads is " << pdf(flip, 0) << endl;
cout << "Probability of getting at least one head is " << 1. - pdf(flip, 0) << endl;

Когда мы хотим вычислить вероятность для диапазона или значений, мы можем суммировать PDF:

cout << "Probability of getting 0 or 1 heads is "
  << pdf(flip, 0) + pdf(flip, 1) << endl; // sum of exactly == probabilities

Можно использовать CDF.

cout << "Probability of getting 0 or 1 (<= 1) heads is " << cdf(flip, 1) << endl;
cout << "Probability of getting 9 or 10 heads is " << pdf(flip, 9) + pdf(flip, 10) << endl;

Обратите внимание, что используя

cout << "Probability of getting 9 or 10 heads is " << 1. - cdf(flip, 8) << endl;

менее точным, чем использование комплемента.

cout << "Probability of getting 9 or 10 heads is " << cdf(complement(flip, 8)) << endl;

Поскольку вычитание может включатьошибку отмены, где какcdfдополнениеперевернуть,8)не использует внутренне такое вычитание и поэтому не проявляет проблемы.

Чтобы получить вероятность для ряда голов, мы можем добавить pdf для каждого числа голов.

cout << "Probability of between 4 and 6 heads (4 or 5 or 6) is "
  //  P(X == 4) + P(X == 5) + P(X == 6)
  << pdf(flip, 4) + pdf(flip, 5) + pdf(flip, 6) << endl;

Но это, вероятно, менее эффективно, чем использование cdf.

cout << "Probability of between 4 and 6 heads (4 or 5 or 6) is "
  // P(X <= 6) - P(X <= 3) == P(X < 4)
  << cdf(flip, 6) - cdf(flip, 3) << endl;

Конечно, для большего диапазона, например, от 3 до 7

cout << "Probability of between 3 and 7 heads (3, 4, 5, 6 or 7) is "
  // P(X <= 7) - P(X <= 2) == P(X < 3)
  << cdf(flip, 7) - cdf(flip, 2) << endl;
cout << endl;

Наконец, напечатайте две таблицы вероятности дляточноипо меньшей мереряда голов.

// Print a table of probability for the exactly a number of heads.
cout << "Probability of getting exactly (==) heads" << endl;
for (int successes = 0; successes <= flips; successes++)
{ // Say success means getting a head (or equally success means getting a tail).
  double probability = pdf(flip, successes);
  cout << left << setw(2) << successes << "     " << setw(10)
    << probability << " or 1 in " << 1. / probability
    << ", or " << probability * 100. << "%" << endl;
} // for i
cout << endl;
// Tabulate the probability of getting between zero heads and 0 upto 10 heads.
cout << "Probability of getting upto (<=) heads" << endl;
for (int successes = 0; successes <= flips; successes++)
{ // Say success means getting a head
  // (equally success could mean getting a tail).
  double probability = cdf(flip, successes); // P(X <= heads)
  cout << setw(2) << successes << "        " << setw(10) << left
    << probability << " or 1 in " << 1. / probability << ", or "
    << probability * 100. << "%"<< endl;
} // for i

Последнее (от 0 до 10 голов) должно, конечно, быть 100% вероятностью.

}
catch(const std::exception& e)
{
  //

Всегда важно включать пробные блоки; ловить блоки, потому что политика по умолчанию заключается в том, чтобы бросать исключения на аргументы, которые не являются доменом или вызывают ошибки, такие как численный переполнение.

Отсутствие пробы & ловить блоки, программа прекратит, в то время как сообщение ниже из брошенного исключения даст некоторые полезные подсказки о причине проблемы.

  std::cout <<
    "\n""Message from thrown exception was:\n   " << e.what() << std::endl;
}

См.binomial_coinflip_example.cppдля полного исходного кода, вывод программы выглядит следующим образом:

Using Binomial distribution to predict how many heads and tails.
From 10 one can expect to get on average 5 heads (or tails).
Mode is 5
Standard deviation is 1.581
So about 2/3 will lie within 1 standard deviation and get between 4 and 6 correct.
Skewness is 0
Skewness if success_fraction is 0.5 is 0
For 10 coin flips:
Probability of getting no heads is 0.0009766
Probability of getting at least one head is 0.999
Probability of getting 0 or 1 heads is 0.01074
Probability of getting 0 or 1 (<= 1) heads is 0.01074
Probability of getting 9 or 10 heads is 0.01074
Probability of getting 9 or 10 heads is 0.01074
Probability of getting 9 or 10 heads is 0.01074
Probability of between 4 and 6 heads (4 or 5 or 6) is 0.6562
Probability of between 4 and 6 heads (4 or 5 or 6) is 0.6563
Probability of between 3 and 7 heads (3, 4, 5, 6 or 7) is 0.8906
Probability of getting exactly (==) heads
0      0.0009766  or 1 in 1024, or 0.09766%
1      0.009766   or 1 in 102.4, or 0.9766%
2      0.04395    or 1 in 22.76, or 4.395%
3      0.1172     or 1 in 8.533, or 11.72%
4      0.2051     or 1 in 4.876, or 20.51%
5      0.2461     or 1 in 4.063, or 24.61%
6      0.2051     or 1 in 4.876, or 20.51%
7      0.1172     or 1 in 8.533, or 11.72%
8      0.04395    or 1 in 22.76, or 4.395%
9      0.009766   or 1 in 102.4, or 0.9766%
10     0.0009766  or 1 in 1024, or 0.09766%
Probability of getting upto (<=) heads
0         0.0009766  or 1 in 1024, or 0.09766%
1         0.01074    or 1 in 93.09, or 1.074%
2         0.05469    or 1 in 18.29, or 5.469%
3         0.1719     or 1 in 5.818, or 17.19%
4         0.377      or 1 in 2.653, or 37.7%
5         0.623      or 1 in 1.605, or 62.3%
6         0.8281     or 1 in 1.208, or 82.81%
7         0.9453     or 1 in 1.058, or 94.53%
8         0.9893     or 1 in 1.011, or 98.93%
9         0.999      or 1 in 1.001, or 99.9%
10        1          or 1 in 1, or 100%

PrevUpHomeNext

Статья Binomial Coin-Flipping Example раздела Math Toolkit 2.5.0 Binomial Distribution Examples может быть полезна для разработчиков на c++ и boost.




Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.



:: Главная :: Binomial Distribution Examples ::


реклама


©KANSoftWare (разработка программного обеспечения, создание программ, создание интерактивных сайтов), 2007
Top.Mail.Ru

Время компиляции файла: 2024-08-30 11:47:00
2025-07-05 03:46:28/0.0047130584716797/0