处理大数以计算组合数

Handling large numbers to calculate the number of combinations

我写了下面的代码来计算一个概率。我知道我使用的公式是正确的。对于 mn 的小值,该代码给出了合理的结果。但是,对于 mn 的较大值,结果 sumC 在区间之外[0,1] 这不是预期的。变量 iter 取大值可能就是这个原因。我该如何处理这个问题?

import math
from scipy.special import comb
n = 50
m = 100
k = 15
P=[]
sumC = 0
for j in range(k, m+1):
    if not (n-j < 0):
        iter = (-1)**(j+k) * comb(j, k, exact=True) * comb(m, j, exact=True) * math.factorial(n) * (m-j)**(n-j) /( (m)**(n) * math.factorial(n-j))
        sumC = sumC + iter
print(sumC )

使用精度为 50 位的 Python mpmath arbitrary precision library 生成 [0, 1] 范围内的值。

from scipy.special import comb
from mpmath import fac, mp

mp.dps = 50; mp.pretty = True

def compute_prob(k, m, n):
  """ Original summation, but using factorial ('fac') from mpmath """
  sumC = 0
  for j in range(k, m+1):
    if not (n-j < 0):
        iter_ = (-1)**(j+k) * comb(j, k, exact=True) * comb(m, j, exact=True) * fac(n) * (m-j)**(n-j) /( (m)**(n) * fac(n-j))
        sumC = sumC + iter_

  return sumC

n = 50
m = 100
k = 15
print(compute_prob(k, m, n))

输出

0.000054845306977312907595945622368606216050228369266162