python日志n选择k [英] python log n choose k

查看:48
本文介绍了python日志n选择k的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scipy.misc.comb,返回 n 选择 k,使用 gammaln 函数实现.是否有保留在日志空间中的函数?我看到没有 scipy.misc.combln 或任何类似的.自己实现很简单,但如果它已经在某个地方的包中会很方便.我在scipy.misc里没有看到,只是感觉转换成普通空间再回log很浪费.

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.

推荐答案

可以使用 gammaln,但是当 N >>k.这可以通过与 beta 函数的关系来避免:

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)

这篇关于python日志n选择k的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆