二项分布

二项分布_第1张图片二项分布_第2张图片

1 二项分布N,P对分布的影响

 

二项分布_第3张图片

# --*-- coding:utf-8 --*--
import distribution
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
# 二项分布举例:将一个硬币抛三次,用随机变量X记录在三次抛中正面向上的次数,将X的所有可能取值对应的概率算出来


x = range(0, 101)
P_1 = 0.2
p_1 = [distribution.binomial(len(x) - 1, P_1, i) for i in x]
P_2 = 0.8
p_2 = [distribution.binomial(len(x) - 1, P_2, i) for i in x]
x_3 = range(0, 201)
p_3 = [distribution.binomial(len(x_3), P_1, i) for i in x_3]

width = 1

# 不同的P
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax1.xaxis.set_major_locator(MultipleLocator(10))
ax1.bar([i - float(width) / 2 for i in x], p_1, width=width, label='N=%s P=%s' % (len(x) - 1, P_1))
ax1.bar([i - float(width) / 2 for i in x], p_2, width=width, color='r', label='N=%s P=%s' % (len(x) - 1, P_2))
ax1.plot(x, p_1, x, p_2, color='r')
ax1.set_title('binomial distribution')
ax1.legend()
ax1.grid()

# 不同的N
ax2 = fig.add_subplot(122)
ax2.xaxis.set_major_locator(MultipleLocator(10))
ax2.bar([i - float(width) / 2 for i in x], p_1, width=width, label='N=%s P=%s' % (len(x) - 1, P_1))
ax2.bar([i - float(width) / 2 for i in x_3], p_3, width=width, color='r', label='N=%s P=%s' % (len(x_3) - 1, P_1))
ax2.plot(x, p_1, x_3, p_3, color='r')
ax2.set_title('binomial distribution')
ax2.legend()
ax2.grid()

plt.show()



distribution.py
# --*-- coding:utf --*--
import math


def combination(n, k):
    """
    n choose k
    """
    return math.factorial(n) / (math.factorial(k) * math.factorial(n - k))


def Binom(n, k, d={}):
    """Compute the binomial coefficient "n choose k".

    Args:
      n: number of trials
      k: number of successes
      d: map from (n,k) tuples to cached results

    Returns:
      int
    """
    if k == 0:
        return 1
    if n == 0:
        return 0

    try:
        return d[n, k]
    except KeyError:
        res = Binom(n-1, k) + Binom(n-1, k-1)
        d[n, k] = res
        return res


def binomial(n, p, x):
    if x > n:
        return None
    # return combination(n, x) * (p ** x) * ((1 - p) ** (n - x))
    return Binom(n, x) * (p ** x) * ((1 - p) ** (n - x))
2,二巷分布 4重伯努利实验 扔硬币
3,二项分布 n重伯努利试验 射击

你可能感兴趣的:(二项分布)