Stirling's approximation for $n!$¶
Stirling's approximation says that factorials can be approximated as follows: $$ n! \approx \sqrt{2\pi} \; n^{n+1/2} \; e^{-n}. $$ This is useful in statistical physics, for example, where we have to think about $n!$ for very large numbers $n$. It is also theoretically interesting.
In this notebook (which covers roughly the same ground as this video) we will simply plot some graphs to show that the approximation looks plausible.
In [3]:
import math
import numpy as np
import matplotlib.pyplot as plt
In [11]:
def stirling(n):
"""Return Stirling's approximation for n!"""
return np.sqrt(2*np.pi)* n**(n+1/2)*np.exp(-n)
Because the numbers $n!$ grow so quickly, if we just plot them directly we get a picture that is very hard to interpret. It is much better use a logarithmic scale on the $y$-axis, which we do by including the line plt.yscale('log')
. (Try removing that line to see what happens.)
In [13]:
ns = range(1, 21)
xs = np.linspace(1, 20, 100)
plt.xlim(0, 21)
plt.xticks(range(0, 21, 2))
plt.yscale('log')
plt.plot(xs, stirling(xs), 'r-',label='Stirling')
plt.plot(ns, [math.factorial(n) for n in ns], 'b.', label='n!')
plt.legend()
Out[13]:
<matplotlib.legend.Legend at 0x20f25600510>
In [ ]: