Hi,
since binomial distribution is important also in the finance world,
here the source code of a small commandline utility program for
on the fly calculating a table of the distribution values:
since binomial distribution is important also in the finance world,
here the source code of a small commandline utility program for
on the fly calculating a table of the distribution values:
Code:
/*
binomial.cpp
Author: U.M. (user botpro at www.elitetrader.com )
Compile:
g++ -Wall -O2 binomial.cpp -o binomial.exe
Run:
./binomial.exe
See also:
https://en.wikipedia.org/wiki/Binomial_distribution#Example
Example:
For the above wiki example of a biased coin game:
Binomial distribution (where any event is independent of any previous event(s))
p=0.3000(30.00%) n=6 :
k p(k) p(0..k) p(k+1..n)
0 0.11765 0.11765 0.88235
1 0.30253 0.42017 0.57983
2 0.32413 0.74431 0.25569
3 0.18522 0.92953 0.07047
4 0.05953 0.98906 0.01094
5 0.01021 0.99927 0.00073
6 0.00073 1.00000 0.00000
p(k) means: p for exact k consecutive successes in n plays
p(0..k) means: p for at at most k consecutive successes in n plays
p(k+1..n) means: p for at least k consecutive successes in n plays
*/
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
using namespace std;
int usage(const string AsPgmName, const int AiRc = 1)
{
printf("Usage: %s p n\n", AsPgmName.c_str());
printf("where p=probability for success (p must be between 0 and 1), n=number of plays or events\n");
printf("Some examples for p:\n"
" fair dice game: p=0.16667\n"
" fair coin tossing game: p=0.5\n"
" stock price rising: p=0.5\n");
return AiRc;
}
int main(int argc, char* argv[])
{
printf("Binomial distribution (where any event is independent of any previous event(s))\n");
if (argc < 3) return usage(argv[0], 1);
const double p = atof(argv[1]);
const size_t n = atoi(argv[2]);
const double q = 1.0 - p;
printf("p=%.4f(%.2f%%) n=%zu :\n", p, p * 100.0, n);
printf(" k p(k) p(0..k) p(k+1..n)\n");
double pk = pow(q, n), s = 0;
for (size_t i = 0; i <= n; ++i)
{
if (i)
pk = double(n - i + 1) / double(i) * p / q * pk;
s += pk;
printf("%3zu %.5f %.5f %8.5f\n", i, pk, s, 1.0 - s);
}
printf("p(k) means: p for exact k consecutive successes in n plays\n");
printf("p(0..k) means: p for at most k consecutive successes in n plays\n");
printf("p(k+1..n) means: p for at least k consecutive successes in n plays\n");
return 0;
}
Last edited: