0

所以我决定做一个超几何分布计算器(概率和统计的东西)。问题是输出总是介于 0 和 1 之间。因此 Python 根据输出值向下舍入到 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。谢谢!

4

1 回答 1

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源文件的顶部,您就不必更改其他代码。

于 2012-01-10T00:23:28.277 回答