简体   繁体   中英

Binomial distribution output CDF/PMF using Python

The Python question I am working on requests to create a binomial function, takes four input, last one was true/false. if true returns cdf, and true by default. if false returns pmf. this is what I got so far. Would someone advise me on how to complete the code?

def binomial_distribution(x,n,p,cum):
  """
  Computes the probability of having x successes out of n trials.
  Each trial has a probability of success p
  """
    nCx = combination(n,x)
    q = 1-p
    return nCx*(p**x)*(q**(n-x))

Here is the code required. Things to note are commented below:

def factorial(n): 
    if n == 0: return 1
    factrl = n
    while n > 2:
        n -= 1
        factrl = factrl * n
    return factrl

def combination(n, x):
    return factorial(n)/(factorial(x)*factorial(n-x))

def binomial_distribution(x,n,p,cum = True):
    """
    Computes the probability of having x successes out of n trials.
    Each trial has a probability of success p
    """
    nCx = combination(n,x)
    q = 1-p

    #What helps is a conditional return statement as below
    if cum: return bin_cdf(x, n, p)
    else: return nCx*(p**x)*(q**(n-x))

def bin_cdf(x, n, p):
    cumul = 0.0
    while x > 0:
        print(x)
        cumul += binomial_distribution(x, n, p, False) #Sums using formula
         #This kind of recursion is not only possible but encouraged
        x -= 1
    return cumul

The results have been verified using a third party calculator. Please also note it does not handle errors. Good programs also test if the values input are also valid (eg that n is always bigger than x and p is an appropriate probability value in the range [0,1] )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM