Python implements binomial distribution algorithm - self-made probability calculator

Python implements binomial distribution algorithm - self-made probability calculator

The binomial distribution (Binomial Distribution) is a discrete probability distribution that can be used to describe the probability distribution of k successes in n independent Bernoulli trials. It is the basis of many statistical knowledge and practical problems.

As a powerful programming language, Python also has a very wide range of applications in statistics. We can use Python to write a simple program and input the specified parameters to automatically calculate the probability of the binomial distribution.

The following is the implementation code of Python:

import math

def binomial_distribution(n, k, p):
    # 计算组合数
    c = math.comb(n, k)
    # 计算概率
    prob = c * p ** k * (1 - p) ** (n - k)
    # 返回结果
    return prob

In the above code, we use the math library in Python to calculate the number of combinations, and calculate the probability of the binomial distribution according to the formula. Among them, n represents the number of trials, k represents the number of successes, and p represents the probability of each success.

We can use this code to calculate the probability of 5 successes out of 10 independent Bernoulli trials:

>>> binomial_distribution(10, 5, 0.5)
0.24609375

If multiple sets of data need to be calculated, we can write a for loop to calculate in batches:

for i in range(11):
    print(f"在10次独立的伯努利试验中,成功{i}次的概率为:{binomial_distribution(10, i, 0.5)}")

The result of the operation is as follows:

在10次独立的伯努利

Guess you like

Origin blog.csdn.net/update7/article/details/131040244