简体   繁体   English

使用Python的二项分布输出CDF / PMF

[英]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. 我正在处理创建二项式函数的请求的Python问题,需要四个输入,最后一个输入是true / false。 if true returns cdf, and true by default. 如果为true,则返回cdf,默认情况下为true。 if false returns pmf. 如果为false,则返回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] ) 好的程序还会测试输入的值是否也有效(例如n总是大于xp[0,1]范围内的适当概率值)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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