Stirling’s approximation is a mathematical formula used to estimate a factorial of a large number. It is named after the mathematician James Stirling. Stirling’s approximation is used in many engineering fields, including probability theory, statistical mechanics, mathematics, and computer science (CS).
The formula is given as follows:
where,
This formula estimates and becomes more accurate as gets larger.
Apart from mathematics and engineering. Stirling’s approximation is used in computer science as well. It is generally used in the complexity analysis of an algorithm. The factorial function is a commonly encountered mathematical operation in many algorithms, and calculating the exact value of can be computationally expensive for large values of .
With the help of Stirling’s approximation formula, we can estimate the value of without having to calculate the exact value. This can significantly reduce the algorithm’s computational complexity.
Let’s look at an example.
Let’s solve the by a conventional method, which is:
The code for this approach is as follows:
def factorial(n):result = 1for i in range(1, n+1):result *= ireturn resultprint(factorial(100))
Here, factorial(n)
denotes the factorial of n
. The time complexity of this algorithm is dominated by the time required to compute factorials, which is for each factorial.
Now let’s see how Stirling’s approximation approach can help us in exact approximation. Using Stirling’s approximation, we can estimate the factorial of as:
Let’s see the code to implement Stirling’s approximation:
import mathdef factorial_stirling(n):return math.sqrt(2 * math.pi * n) * ((n / math.e) ** n)n = 100approximation = factorial_stirling(n)print(approximation)
Note: Please note that Stirling’s approximation is an estimation technique, and the
may not be the exact factorial value. It provides a close approximation, especially for large values of result For n=100, Exact value of n! = 9.33262154439e+157. With Stirling’s approximation: n! = 9.32484762526e+157. As, the value of n increases the approximation of factorial with Stirling’s approximation become more accurate. .
Since the time complexity for calculating is . So, the total time complexity for Stirling’s approximation will be .
Which is a more accurate estimate than the estimate obtained by assuming that the factorials are computed exactly.
Free Resources