Untitled

mail@pastecode.io avatar
unknown
plain_text
4 months ago
1.3 kB
1
Indexable
#include <iostream>
#include <cmath>
#include <iomanip>
#include <vector>

using namespace std;

// Function to calculate binomial coefficient
int binomialCoefficient(int n, int k) {
    if (k > n) return 0;
    if (k == 0 || k == n) return 1;
    int res = 1;
    for (int i = 0; i < k; ++i) {
        res *= (n - i);
        res /= (i + 1);
    }
    return res;
}

// Function to calculate binomial probability
double binomialProbability(int n, int k, double p) {
    return binomialCoefficient(n, k) * pow(p, k) * pow(1 - p, n - k);
}

int main() {
    const int n = 3; // number of trials (coins)
    const double p = 0.3; // probability of heads
    const int totalTosses = 100; // total number of trials

    vector<double> probabilities(4);
    vector<double> expectedFrequencies(4);

    // Calculate binomial probabilities and expected frequencies
    for (int k = 0; k <= n; ++k) {
        probabilities[k] = binomialProbability(n, k, p);
        expectedFrequencies[k] = probabilities[k] * totalTosses;
    }

    // Print the results
    cout << fixed << setprecision(2);
    cout << "Number of Heads\tProbability\tExpected Frequency\n";
    for (int k = 0; k <= n; ++k) {
        cout << k << "\t\t" << probabilities[k] << "\t\t" << expectedFrequencies[k] << "\n";
    }

    return 0;
}
Leave a Comment