Bernoulli scheme#11726

Bernoulli scheme (Анализа на решението)

A Bernoulli trial is an experiment with two possible outcomes:

A trial is called "Bernoulli" if it is independent and the probability of success remains constant throughout all trials.

The Bernoulli trial scheme is a series of independent trials, each of which is a Bernoulli trial. Let the number of trials be denoted by . In each trial, the probability of success is and the probability of failure is 1 - p, and these probabilities remain constant.

An example could be repeatedly flipping a coin. If we are interested in how many times heads will appear out of flips, this would represent a Bernoulli trial scheme.

The number of successes in a series of Bernoulli trials follows a binomial distribution. Let be a random variable representing the number of successes in trials. Then:

P(X = k) = C_n^k \cdot p^k \cdot (1 - p)^{n - k}

where

Proof. Consider a specific sequence of trials in which:

Since the trials are independent, the probability of this particular sequence is equal to the product of the probabilities of the individual trials:

To obtain exactly successes, we need to choose the positions in which they will occur. The number of such choices is given by the binomial coefficient C_n^k.

Therefore, the probability of having exactly successes is

P(X = k) = C_n^k \cdot p^k \cdot (1 - p)^{n - k}

To compute the value of the binomial coefficient with real numbers, we'll use the following approach:

C_n^k = {n! \over k! (n - k)!}, \\ ln~C_n^k = ln~n! - ln~k! - ln~(n - k)!

It is known that ln~n! = ln~(1 \cdot 2 \cdot ... \cdot n) = ln~1 + ln~2 + ... + ln~n

Store the values of in the cells of an array . Then we calculate

res = ln~n! - ln~k! - ln~(n - k)! = lf[n] - lf[k] - lf[n - k],

After that

C_n^k = e^{res}

Example

In the first test, n = 8 trials are conducted. The probability of event occurring in each trial is p = 0.3. We want to find the probability that event A occurs exactly k = 2 times. The desired probability is:

P(X = 2) = C_8^2 \cdot 0.3^2 \cdot 0.7^6 ≈ 0.296475

Algorithm implementation

Declare an array , where lf[i] = ln~i! = ln~1 + ln~2 + ... + ln~i.

#define MAX 1001
double lf[MAX];

Read the input data.

scanf("%d %d", &n, &k);
scanf("%lf", &p);
q = 1 - p;

Fill the array .

lf[1] = 0;
for (i = 2; i <= n; i++)
  lf[i] = lf[i - 1] + log(i);

Compute the value of the binomial coefficient res = C_n^k.

res = lf[n] - lf[k] - lf[n - k];
res = exp(res);

Compute the answer res = C_n^k \cdot p^k \cdot (1 - p)^{n - k}.

for (i = 0; i < k; i++)
  res = res * p;
for (i = 0; i < n - k; i++)
  res = res * q;

Print the answer.

printf("%lf\n", res);