I need to compute combinatorials (nCr) in Python but cannot find the function to do that in math, numpy or stat libraries. Something
The direct formula produces big integers when n is bigger than 20.
So, yet another response:
from math import factorial
reduce(long.__mul__, range(n-r+1, n+1), 1L) // factorial(r)
short, accurate and efficient because this avoids python big integers by sticking with longs.
It is more accurate and faster when comparing to scipy.special.comb:
>>> from scipy.special import comb
>>> nCr = lambda n,r: reduce(long.__mul__, range(n-r+1, n+1), 1L) // factorial(r)
>>> comb(128,20)
1.1965669823265365e+23
>>> nCr(128,20)
119656698232656998274400L # accurate, no loss
>>> from timeit import timeit
>>> timeit(lambda: comb(n,r))
8.231969118118286
>>> timeit(lambda: nCr(128, 20))
3.885951042175293