python log n choose k

numpy, python, scipy

Solution

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)

Problem

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.

Original source