标签:style blog class code java color
# --*-- 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()
__author__ = ‘root‘ import math def combination(n, k): return math.factorial(n) / (math.factorial(k) * math.factorial(n - k)) def binomial(n, p, x): if x > n: return None return combination(n, x) * (p ** x) * ((1 - p) ** (n - x))
标签:style blog class code java color
原文地址:http://www.cnblogs.com/i80386/p/3706246.html