def make_hist(p, n, num_points): data = [binomial(n, p) for _ in range(num_points)] # use a bar chart to show the actual binomial samples histogram = Counter(data) plt.bar([x - 0.4 for x in histogram.keys()], [v / num_points for v in histogram.values()], 0.8, color="0.75") mu = p * n sigma = math.sqrt(n * p * (1 - p)) # use a line chart to show the normal approximation xs = range(min(data), max(data) + 1) ys = [normal_cdf(i + 0.5, mu, sigma) - normal_cdf(i - 0.5, mu, sigma) for i in xs] plt.plot(xs, ys) plt.title("Binomial Distribution vs. Normal Approximation") plt.show()
def make_hist(p, n, num_points): data = [binomial(n, p) for _ in range(num_points)] histogram = Counter(data) plt.bar([x - 0.4 for x in histogram.keys()], [v / num_points for v in histogram.values()], 0.8, color='0.75') mu = p * n sigma = math.sqrt(n * p * (1 - p)) xs = range(min(data), max(data) + 1) ys = [normal_cdf(i + 0.5, mu, sigma) - normal_cdf(i - 0.5, mu, sigma) for i in xs] plt.plot(xs, ys) plt.title("Binomial Dist. vs. Normal Approximation") plt.show()
def make_hist(p, n, num_points): data = [binomial(n, p) for _ in range(num_points)] # use a bar chart to show the actual binomial samples histogram = Counter(data) plt.bar([x - 0.4 for x in histogram.keys()], [v / num_points for v in histogram.values()], 0.8, color='0.75') mu = p * n sigma = math.sqrt(n * p * (1 - p)) # use a line chart to show the normal approximation xs = range(min(data), max(data) + 1) ys = [normal_cdf(i + 0.5, mu, sigma) - normal_cdf(i - 0.5, mu, sigma) for i in xs] plt.plot(xs, ys) plt.title("Binomial Distribution vs. Normal Approximation") plt.show()
def normal_probability_between(lo, hi, mu=0, sigma=1): return normal_cdf(hi, mu, sigma) - normal_cdf(lo, mu, sigma)
def normal_probability_above(lo, mu=0, sigma=1): return 1 - normal_cdf(lo, mu, sigma)
""" Graph plot for cumulative density function for normal distribution """ from matplotlib import pyplot as plt from distributions import normal_cdf xs = [x / 10.0 for x in range(-50, 50)] plt.plot(xs, [normal_cdf(x, sigma=1) for x in xs], '-', label='mu=0, sigma=1') plt.plot(xs, [normal_cdf(x, sigma=2) for x in xs], '--', label='mu=0, sigma=2') plt.plot(xs, [normal_cdf(x, sigma=0.5) for x in xs], ':', label='mu=0,sigma=0.5') plt.plot(xs, [normal_cdf(x, mu=-1) for x in xs], '-.', label='mu=-1, sigma=1') plt.legend(loc=4) # bottom right plt.title("Various Normal cdfs") plt.show()