Ivan Kelber - 1 year ago 84

Python Question

So I've decided to make a hypergeometric distribution calculator (probability and statistics stuff). The problem is that the output will always be between 0 and 1. So Python rounds down to 0 or up to 1 depending on the output value.

Here's my code

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

I've tried importing the decimal module, but I'm not really sure if I'm using it correctly or if that's even what it's there for. Any help would be awesome!

Edit: As an example, when I set N = 15, n = 6, r = 5, and k = 3, it rounds the answer to 0. I would like it instead to print the proper answer: .2397802398. Thanks!

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Make sure the division returns a float instead of an integer (as all input variables are integers):

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

**Alternative**: I assume you're using Python < 3 (otherwise this issue wouldn't have come up in the first place). Then you could do

```
from __future__ import division
```

which will make `/`

the floating division, whereas `//`

returns integers if given integers. Just put this `import`

at the top of your source file, and you won't have to change your other code.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**