TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
binomial_dist.cpp
Go to the documentation of this file.
1
14#include <cmath>
15#include <iostream>
16
22double binomial_expected(double n, double p) { return n * p; }
23
29double binomial_variance(double n, double p) { return n * p * (1 - p); }
30
36double binomial_standard_deviation(double n, double p) {
37 return std::sqrt(binomial_variance(n, p));
38}
39
47double nCr(double n, double r) {
48 double numerator = n;
49 double denominator = r;
50
51 for (int i = n - 1; i >= ((n - r) + 1); i--) {
52 numerator *= i;
53 }
54
55 for (int i = 1; i < r; i++) {
56 denominator *= i;
57 }
58
59 return numerator / denominator;
60}
61
65double binomial_x_successes(double n, double p, double x) {
66 return nCr(n, x) * std::pow(p, x) * std::pow(1 - p, n - x);
67}
68
74double binomial_range_successes(double n, double p, double lower_bound,
75 double upper_bound) {
76 double probability = 0;
77 for (int i = lower_bound; i <= upper_bound; i++) {
78 probability += nCr(n, i) * std::pow(p, i) * std::pow(1 - p, n - i);
79 }
80 return probability;
81}
82
84int main() {
85 std::cout << "expected value : " << binomial_expected(100, 0.5)
86 << std::endl;
87
88 std::cout << "variance : " << binomial_variance(100, 0.5) << std::endl;
89
90 std::cout << "standard deviation : "
91 << binomial_standard_deviation(100, 0.5) << std::endl;
92
93 std::cout << "exactly 30 successes : " << binomial_x_successes(100, 0.5, 30)
94 << std::endl;
95
96 std::cout << "45 or more successes : "
97 << binomial_range_successes(100, 0.5, 45, 100) << std::endl;
98
99 return 0;
100}
double binomial_x_successes(double n, double p, double x)
double binomial_expected(double n, double p)
double binomial_range_successes(double n, double p, double lower_bound, double upper_bound)
double nCr(double n, double r)
double binomial_variance(double n, double p)
int main()
double binomial_standard_deviation(double n, double p)
Probability algorithms.