Sunday, February 1, 2015

py5. Cumulative Binomial Distribution in Python

We can use scipy.stats.binom.cdf to find cumulative binomial distribution probabilities.


This is contrasted to a uniform distribution generated from 1000 trials, each of size of 100.


The probability of success is 0.5 so the number of successful outcomes ranges from 0 to 100 with 50 most likely.

# ex5.py
from __future__ import division, print_function
from numpy.random import rand
from scipy.stats import binom
import numpy as np
import matplotlib.pyplot as plt
num_trials = 1000
each_trial = 100
p = 0.5
x = np.arange(each_trial+1)
sig = np.zeros(num_trials)
sig1 = binom.cdf(x, n = each_trial, p = p)
for t in range(num_trials):
    tr = rand(each_trial)
    sig[t] = sum(tr<=p)
sigc = np.zeros(len(x))
for i in x:
  sigc[i] = sum(sig==i)
plt.title('Cumulative Binomial Distribution')
plt.plot(x, sigc.cumsum()/num_trials, 'r', 
         x, sig1, 'g')
plt.xlabel('Successes in %d' % each_trial)
plt.ylabel('Cumulative Probability')
plt.show()

Output:

No comments:

Post a Comment