Factorial of a large number in python

后端 未结 9 830
灰色年华
灰色年华 2020-12-29 12:32

Here\'s my approach to factorials:

def factorial(n):
    \'\'\'Returns factorial of n\'\'\'
    r = 1
    for i in range(1, n + 1):
        r *= i
    return         


        
9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 13:26

    It's actually unusual to really need the true factorial value n! in many areas of application. Often it's way more realistic to use the natural log of the factorial. I can't think of any applications where the log can't be used as a better alternative, because factorials are most often used to compute values related to probabilities of choosing combinations of things.

    A common thing to compute is probabilities that are based on factorials such as choosing the binomial coefficient (n k) = n! / (k!(n-k)!). Given this is a ratio of factorials then log(n k) = log(n!)-log(k!)-log((n-k)!) which is reliably computed using one of the various log factorial approximations. And if you do a lot of probability math it's generally best to do it in the log domain anyway (measuring probability in decibels) because it often involves extremely wide ranges of numbers less than 1, and so math precision will fall apart very quickly using common floating point representations if the log version is not used.

    E.T.Jaynes was a famous mathematician and an expert in probability theory and I'd recommend his book "Probability Theory: The Logic of Science" as a very readable source on this topic and Bayesian reasoning and information theory using log probabilities.

提交回复
热议问题