`scipy.misc.comb`比ad-hoc二项式计算更快吗?

alv*_*vas 31 python math combinations combinatorics scipy

是否确定现在scipy.misc.comb确实比特别实施更快?

根据一个旧的答案,统计:Python中的组合,这个自制函数比scipy.misc.comb计算组合时更快nCr:

def choose(n, k):
    """
    A fast way to calculate binomial coefficients by Andrew Dalke (contrib).
    """
    if 0 <= k <= n:
        ntok = 1
        ktok = 1
        for t in xrange(1, min(k, n - k) + 1):
            ntok *= n
            ktok *= t
            n -= 1
        return ntok // ktok
    else:
        return 0
Run Code Online (Sandbox Code Playgroud)

但是在我自己的机器上运行一些测试后,使用这个脚本似乎不是这样的:

from scipy.misc import comb
import random, time

def choose(n, k):
    """
    A fast way to calculate binomial coefficients by Andrew Dalke (contrib).
    """
    if 0 <= k <= n:
        ntok = 1
        ktok = 1
        for t in xrange(1, min(k, n - k) + 1):
            ntok *= n
            ktok *= t
            n -= 1
        return ntok // ktok
    else:
        return 0

def timing(f):
    def wrap(*args):
        time1 = time.time()
        ret = f(*args)
        time2 = time.time()
        print '%s function took %0.3f ms' % (f.__name__, (time2-time1)*1000.0)
        return ret
    return wrap

@timing
def test_func(combination_func, nk):
    for n,k in nk:
        combination_func(n, k)

nk = []
for _ in range(1000):
    n = int(random.random() * 10000)
    k = random.randint(0,n)
    nk.append((n,k))

test_func(comb, nk)
test_func(choose, nk)
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

$ python test.py
/usr/lib/python2.7/dist-packages/scipy/misc/common.py:295: RuntimeWarning: overflow encountered in exp
  vals = exp(lgam(N+1) - lgam(N-k+1) - lgam(k+1))
999
test_func function took 32.869 ms
999
test_func function took 1859.125 ms

$ python test.py
/usr/lib/python2.7/dist-packages/scipy/misc/common.py:295: RuntimeWarning: overflow encountered in exp
  vals = exp(lgam(N+1) - lgam(N-k+1) - lgam(k+1))
999
test_func function took 32.265 ms
999
test_func function took 1878.550 ms
Run Code Online (Sandbox Code Playgroud)

时间分析测试是否表明新scipy.misc.comb的比ad-hoc choose()功能更快?我的测试脚本上是否有任何错误导致时间不准确?

为什么scipy.misc.comb现在更快?这是因为一些cython/ c包装技巧?


EDITED

在@WarrenWeckesser评论之后:

使用时使用默认浮点近似scipy.misc.comb(),由于浮点溢出,计算中断.

(有关文档,请参阅http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.misc.comb.html)

exact=True使用下面的函数测试使用长整数而不是浮点计算时,计算1000种组合时要慢得多:

@timing
def test_func(combination_func, nk):
    for i, (n,k) in enumerate(nk):
        combination_func(n, k, exact=True)
Run Code Online (Sandbox Code Playgroud)

[OUT]:

$ python test.py
test_func function took 3312.211 ms
test_func function took 1764.523 ms

$ python test.py
test_func function took 3320.198 ms
test_func function took 1782.280 ms
Run Code Online (Sandbox Code Playgroud)

小智 1

参考scipy.misc.comb的源代码,结果的更新例程为:

    val = 1
    for j in xrange(min(k, N-k)):
        val = (val*(N-j))//(j+1)
    return val
Run Code Online (Sandbox Code Playgroud)

而您建议的更新例程是:

    ntok = 1
    ktok = 1
    for t in xrange(1, min(k, n - k) + 1):
        ntok *= n
        ktok *= t
        n -= 1
    return ntok // ktok
Run Code Online (Sandbox Code Playgroud)

我猜测 SciPy 的实现速度较慢的原因是子例程在每次迭代时都涉及整数除法,而您的子例程仅在 return 语句中调用除法一次。