0
0
SciPydata~5 mins

Binomial distribution in SciPy

Choose your learning style9 modes available
Introduction

The binomial distribution helps us find the chance of a certain number of successes in a fixed number of tries, when each try has the same chance of success.

Counting how many heads appear when flipping a coin 10 times.
Finding the chance of getting exactly 3 defective items in a batch of 20.
Estimating how many customers will buy a product out of 100 visitors, if each has a 5% chance to buy.
Checking the probability of passing a multiple-choice quiz by guessing answers.
Syntax
SciPy
from scipy.stats import binom

binom.pmf(k, n, p)
binom.cdf(k, n, p)

binom.pmf(k, n, p) gives the probability of exactly k successes in n tries.

binom.cdf(k, n, p) gives the probability of up to k successes (0 to k).

Examples
This finds the chance of getting exactly 3 heads when flipping a fair coin 5 times.
SciPy
from scipy.stats import binom

# Probability of exactly 3 heads in 5 coin flips
prob_3_heads = binom.pmf(3, 5, 0.5)
print(prob_3_heads)
This finds the chance of getting 0, 1, 2, or 3 defective items if each has a 10% defect chance.
SciPy
from scipy.stats import binom

# Probability of 3 or fewer defective items in 10 tries
prob_up_to_3 = binom.cdf(3, 10, 0.1)
print(prob_up_to_3)
Sample Program

This program calculates the chance of getting exactly 4 successes and also 4 or fewer successes in 10 tries, where each try has a 30% chance of success.

SciPy
from scipy.stats import binom

# Number of trials
n = 10
# Probability of success on each trial
p = 0.3

# Calculate probability of exactly 4 successes
k = 4
prob_exact_4 = binom.pmf(k, n, p)

# Calculate probability of 4 or fewer successes
prob_up_to_4 = binom.cdf(k, n, p)

print(f"Probability of exactly {k} successes: {prob_exact_4:.4f}")
print(f"Probability of {k} or fewer successes: {prob_up_to_4:.4f}")
OutputSuccess
Important Notes

The binomial distribution assumes each trial is independent and has the same chance of success.

Use pmf for exact counts and cdf for cumulative counts.

Summary

Binomial distribution models the number of successes in fixed tries with same success chance.

Use binom.pmf for exact success counts.

Use binom.cdf for cumulative success counts up to a number.