Since it is a discrete distribution we are dealing with here, we will need to use scipy.optimize
The first part is easy:
In [131]:
import scipy.stats as ss
import scipy.optimize as so
In [132]:
ss.binom.pmf(range(12), n=12, p=0.1)
Out[132]:
array([ 2.82429536e-01, 3.76572715e-01, 2.30127770e-01,
8.52325076e-02, 2.13081269e-02, 3.78811145e-03,
4.91051484e-04, 4.67668080e-05, 3.24769500e-06,
1.60380000e-07, 5.34600000e-09, 1.08000000e-10])
For the second part, we need to solve N form the equation PMF(4, N, 0.1)=0.5/0.1/0.05/0.01, by scipy.optimize
, and we need the Nelder-Mead
optimizer, which do not require information from the derivatives and thus suitable for the discrete problem we are facing.
In [133]:
for P in [0.5, 0.1, 0.05, 0.01]:
N=int(so.fmin(lambda n, p: (ss.binom.pmf(4, int(n), 0.1)-p)**2, 40, args=(P,), disp=0))
#the initial guess is 40, because 40*0.1=4
print N,
print ss.binom.pmf(4, N, p=0.1)
39 0.205887043441
67 0.100410451946
81 0.0498607360095
107 0.00999262321 #need to pick 107 crystals in order to be sure 99% of time that there are at least 4 usable crystals.