2016-11-27 1 views
0

파이썬 질문 저는 이항 함수를 생성하기위한 요청에 대해 작업 중이며 4 개의 입력을받습니다. 마지막 하나는 참/거짓입니다. true이면 cdf를 반환하고 기본적으로 true를 반환합니다. 거짓이면 pmf를 반환합니다. 이것이 내가 지금까지 얻은 것입니다. 누군가 코드를 완성하는 방법에 대해 조언 해 주시겠습니까?이항 분포 출력 파이썬을 사용하는 CDF/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)) 
+2

지금까지 무엇이 잘못 되었습니까? –

답변

0

여기에 필요한 코드가 있습니다. 메모 할 내용은 다음과 같습니다.

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 

결과는 타사 계산기를 사용하여 검증되었습니다. 또한 오류를 처리하지 않습니다. 올바른 프로그램은 또한 입력 값이 유효한지 여부도 테스트합니다 (예 : 이 x보다 크고 이 [0,1] 범위의 적절한 확률 값)

관련 문제