python log n choose k

我的未来我决定 提交于 2021-01-27 12:29:17

问题


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.


回答1:


Looking at the source code, it seems like you're right that it would be trivial to implement, but that it likely isn't implemented elsewhere in scipy. On the plus side, there's some error checking going on, so you could eliminate some if you do those checks elsewhere (this is similar to getting rid of the exponential). If you know you'll always give 0 <= k <= N, and each of k, N as an array, then it is down to:

    from scipy import special

    def chooseln(N, k)
      return special.gammaln(N+1) - special.gammaln(N-k+1) - special.gammaln(k+1)



回答2:


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)


来源:https://stackoverflow.com/questions/21767690/python-log-n-choose-k

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!