counting combinations and permutations efficiently

后端 未结 13 1959
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 12:38

I have some code to count permutations and combinations, and I\'m trying to make it work better for large numbers.

I\'ve found a better algorithm for permutations th

13条回答
  •  春和景丽
    2020-12-02 13:07

    Two fairly simple suggestions:

    1. To avoid overflow, do everything in log space. Use the fact that log(a * b) = log(a) + log(b), and log(a / b) = log(a) - log(b). This makes it easy to work with very large factorials: log(n! / m!) = log(n!) - log(m!), etc.

    2. Use the gamma function instead of factorial. You can find one in scipy.stats.loggamma. It's a much more efficient way to calculate log-factorials than direct summation. loggamma(n) == log(factorial(n - 1)), and similarly, gamma(n) == factorial(n - 1).

提交回复
热议问题