Sunday, February 1, 2015

py4. Binomial Distribution in Python

We can use numpy.random.binomial to create distributions based on binomial distribution.


The probability of success, here, is p = 0.5. We conduct 1000 trials, each of a size of 100. Thus the number of successes for each of 1000 trials is between 0 and 100, but near 50, because of 0.5 probability.

# ex4.py
from __future__ import division, print_function
from numpy.random import binomial,  rand
import numpy as np
import matplotlib.pyplot as plt
num_trials = 1000
each_trial = 100
p = 0.5
sig = np.zeros(num_trials)
sig1 = binomial(each_trial,p,num_trials)
for t in range(num_trials):
    tr = rand(each_trial)
    sig[t] = sum(tr<=p)
plt.subplot(211)
plt.title('Trials')
plt.ylabel('Frequency')
plt.hist(sig, range=(30,70), bins = 20, color = 'r')
plt.subplot(212)
plt.hist(sig1, range=(30,70), bins = 20, color = 'g')
plt.xlabel('Successes in %d' % each_trial)
plt.ylabel('Frequency')
plt.show()

Output:


No comments:

Post a Comment