Write your own implementation of the cumulative distribution function for the Binomial distribution. Your function should be called binom_cdf
and take in x, p, N
as arguments. It should return the probability of a sample between 0
and x
, including x
. It should return None
if the arguments are invalid (e.g., x = 'foo'
or p = -4
or x = -4
)
In [31]:
#The points awarded this cell corresopnd to partial credit and/or documentation
### BEGIN SOLUTION
import numpy as np
from scipy.special import binom
def binom_cdf(x, p, N):
'''The binomial distribution cumulative probability function
Args:
x: the inclusive upper bound
p: the probability of success
N: the number of trials of the binomial
returns: the sum of probability of samples from 0 to x
'''
if(type(x) != int or type(x) != int or type(N) != int):
return None
if(p < 0 or p > 1):
return None
if(N < 1):
return None
if x < 0 or x > N:
return None
n = np.arange(0,x + 1)
Pn = binom(N, n) * p**n * (1 - p)**(N - n)
return np.sum(Pn)
### END SOLUTION
In [32]:
'''Check that your answer is correct on some test inputs using scipy stats'''
from numpy import testing as t
import scipy.stats as ss
t.assert_almost_equal( binom_cdf(2, 0.5, 5), ss.binom.cdf(2, p=0.5, n=5) )
### BEGIN HIDDEN TESTS
t.assert_almost_equal( binom_cdf(2, 0.1, 5), ss.binom.cdf(2, p=0.1, n=5) )
t.assert_almost_equal( binom_cdf(0, 0.7, 15), ss.binom.cdf(0, p=0.7, n=15) )
### END HIDDEN TESTS
In [33]:
'''Check that your answer deals with invalid input correclty'''
from numpy import testing as t
import scipy.stats as ss
t.assert_equal( binom_cdf('test', 0.5, 5), None)
### BEGIN HIDDEN TESTS
t.assert_equal( binom_cdf(-4, 0.5, 5), None)
t.assert_equal( binom_cdf(6, 0.5, 5), None)
t.assert_equal( binom_cdf(2, 5, 5), None)
t.assert_equal( binom_cdf(2, 0.4, -4), None)
### END HIDDEN TESTS