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
Two fairly simple suggestions:
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.
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)
.