Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python log n choose k

scipy.misc.comb, returning n choose k, is implemented using the gammaln function. Is there a function that stays in log space? I see there is no scipy.misc.combln or any similar. It is trivial to implement myself, but it would be convenient if it were already in a package somewhere. I don't see it in scipy.misc, and it just feels wasteful to convert to normal space and then back to log.

like image 300
hawkjo Avatar asked Jul 25 '26 02:07

hawkjo


1 Answers

It's possible to use gammaln, but precision is lost in subtractions when N >> k. This can be avoided via the relation to the beta function:

from numpy import log
from scipy.special import betaln

def binomln(n, k):
    # Assumes binom(n, k) >= 0
    return -betaln(1 + n - k, 1 + k) - log(n + 1)
like image 120
pv. Avatar answered Jul 27 '26 15:07

pv.