# Hypergeometric distribution

Paul Rubin http
Wed Jan 4 16:02:04 EST 2006

```"Raven" <balckraven at gmail.com> writes:
> The problem with Stirling's approximation is that I need to calculate
> the hypergeometric hence the factorial for numbers within a large range
> e.g. choose(14000,170) or choose(5,2)

Stirling's approximation to second order is fairly accurate even at
low values:

from math import log,exp,pi

def stirling(n):
# approx log(n!)
return n*(log(n)-1) + .5*(log(2.*pi*n)) + 1/(12.*n)

>>> for n in range(1,6): print n, exp(stirling(n))
...
1 1.00227444918
2 2.00065204769
3 6.00059914247
4 24.0010238913
5 120.002637086
>>>

To third order it's even better:

from math import log,exp,pi

def stirling(n):
# approx log(n!)
return n*(log(n)-1) + .5*(log(2.*pi*n)) + 1/(12.*n) - 1/(360.*n*n*n)

>>> for n in range(1,6): print n, exp(stirling(n))
...
1 0.999494216712
2 1.99995749743
3 5.99998182863
4 23.9999822028
5 119.999970391
>>>

Reference: http://en.wikipedia.org/wiki/Stirling's_approximation

```