2012-01-10 27 views
0

所以我决定制作一个超几何分布计算器(概率和统计数据)。问题是输出总是在0和1之间。所以根据输出值的不同,Python会舍入到0或1。无法输出十进制近似值; Python 2将分数舍入为0或1

这里是我的代码

from combinatorics import combination 
from combinatorics import permutation 
from factorial import factorial 
from decimal import Decimal 

#Hypergeometric and Binomial Distributions! 



def hypergeometric(N, n, r, k): 
    hyper = (combination(r, k) * combination(N - r, n - k))/(combination(N, n)) 
    return hyper 

pop = int(raw_input("What is the size of the population? ")) 
draws = int(raw_input("How many draws were there? ")) 
spop = int(raw_input("What is the smaller population? ")) 
success = int(raw_input("How many successes were there? ")) 

print Decimal(hypergeometric(pop, draws, spop, success)) 

我试着输入十进制模块,但我真的不知道,如果我正确或者如果甚至什么它是有使用它。任何帮助都是极好的!编辑:例如,当我设置N = 15,n = 6,r = 5和k = 3时,它将答案舍入为0.我希望它打印正确答案:.2397802398 。谢谢!

回答

3

确保部门返回的不是整数浮点数(就像所有的输入变量是整数):

def hypergeometric(N, n, r, k): 
    return 1.0 * combination(r, k) * combination(N - r, n - k)/combination(N, n) 

替代:我假设你正在使用Python < 3(否则这个问题止跌”首先出现)。然后,如果给定的整数,你可以做

from __future__ import division 

这将使/浮动师,而//返回一个整数。只需将此import放在源文件的顶部,就不必更改其他代码。

+0

谢谢!这有诀窍,尽管现在我需要努力围绕一些更易于管理的方法来回答问题。 – 2012-01-10 00:25:59

+0

@IvanKelber:为此你可以使用'round'或者类似的 – 2012-01-10 00:28:50

+0

你知道有'round'吗? http://docs.python.org/library/functions.html#round但是,我会保留所有的精度,并且只使用格式化字符串(例如'“%.3f”')在输出中循环。 – 2012-01-10 00:29:18

相关问题