Python - Binomial Distribution

Python - Binomial Distribution

The binomial distribution is a discrete probability distribution that describes the number of successes in a fixed number of independent Bernoulli trials, each with the same probability of success.

For a random variable X following a binomial distribution:

  • X ~ B(n,p)
  • Where:
    • n is the number of trials
    • p is the probability of success on an individual trial

The probability P(X=k) of observing k successes is given by:

P(X=k)=(kn​)pk(1−p)n−k

Where:

  • (kn​) is the binomial coefficient, defined as k!(n−k)!n!​

Using Python to Work with Binomial Distribution

The numpy and scipy.stats libraries in Python provide functionalities to work with the binomial distribution.

1. Generating Random Numbers from a Binomial Distribution:

Using numpy:

import numpy as np n = 10 # number of trials p = 0.5 # probability of success samples = np.random.binomial(n, p, 1000) # Generates 1000 random numbers from B(10, 0.5) 

2. Calculating Binomial Probabilities:

Using scipy.stats:

from scipy.stats import binom n = 10 p = 0.5 # Probability of exactly 5 successes prob_5 = binom.pmf(5, n, p) print(prob_5) 

3. Cumulative Probabilities:

# Probability of 5 or fewer successes cum_prob_5_or_less = binom.cdf(5, n, p) print(cum_prob_5_or_less) 

4. Mean, Variance, Skewness, and Kurtosis:

mean, var, skew, kurt = binom.stats(n, p, moments='mvsk') print("Mean:", mean) print("Variance:", var) print("Skewness:", skew) print("Kurtosis:", kurt) 

These functions and methods can help in understanding and computing various properties and characteristics of the binomial distribution using Python.


More Tags

unique-id scale savechanges keycloak-services android-wifi google-custom-search barcode parallax tree-traversal spring-jms

More Programming Guides

Other Guides

More Programming Examples