繁体   English   中英

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

[英]Binomial distribution output CDF/PMF using Python

我正在处理创建二项式函数的请求的Python问题,需要四个输入,最后一个输入是true / false。 如果为true,则返回cdf,默认情况下为true。 如果为false,则返回pmf。 这就是我到目前为止所得到的。 有人会建议我如何完成代码吗?

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))

这是所需的代码。 注意事项评论如下:

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

结果已使用第三方计算器进行了验证。 另请注意,它不处理错误。 好的程序还会测试输入的值是否也有效(例如n总是大于xp[0,1]范围内的适当概率值)

暂无
暂无

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

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