Factorials, Stirling and the Iterated Logarithm
Two functions sit at the far ends of the growth ladder. The factorial grows faster than any exponential , and it is the number of orderings of items, so it appears in every analysis that reasons about permutations, from the sorting lower bound to random shuffles. The iterated logarithm grows so slowly that it is at most 5 for every input that fits in the universe, yet it is not a constant, and it shows up in the running times of real data structures. Between them, this lesson also meets the Fibonacci numbers and the golden ratio, the classic example of exponential growth with an irrational base.
The ladder so far, from Polynomials, Exponentials and Logarithms: .
Factorials and two easy bounds
, with . Two crude bounds already decide most questions:
- Upper: each of the factors is at most , so .
- Lower: the largest factors are each at least , so .
Taking logarithms of both bounds gives
and the left side is at least once (because when ). Therefore
This one line is the reason no comparison sort can beat : a comparison sort must distinguish all orderings, and yes/no comparisons can distinguish at most of them, so it needs . The next course, Sorting and Order Statistics, proves this in full.
import math
print(f"{'n':>8} {'lg(n!)':>12} {'n lg n':>12} {'ratio':>7}")
for n in [4, 16, 64, 256, 1024, 4096]:
lg_fact = math.log2(math.factorial(n))
print(f"{n:>8} {lg_fact:12.1f} {n * math.log2(n):12.1f} {lg_fact / (n * math.log2(n)):7.3f}") n lg(n!) n lg n ratio
4 4.6 8.0 0.573
16 44.3 64.0 0.691
64 296.0 384.0 0.771
256 1684.0 2048.0 0.822
1024 8769.0 10240.0 0.856
4096 43250.0 49152.0 0.880
The ratio climbs toward 1, but slowly. The crude bounds only promise a ratio between and 1; Stirling's formula explains the slow approach.
Stirling's approximation
The relative error is about , so the approximation is already within 1 percent at and within 0.1 percent at . The program checks both claims: the ratio of to the formula tends to 1, and times the excess tends to 1 as well.
import math
def stirling(n):
return math.sqrt(2 * math.pi * n) * (n / math.e) ** n
print(f"{'n':>4} {'n! / Stirling':>14} {'12n (ratio - 1)':>16}")
for n in [1, 2, 5, 10, 20, 50, 100, 170]:
r = math.factorial(n) / stirling(n)
print(f"{n:>4} {r:14.6f} {12 * n * (r - 1):16.4f}") n n! / Stirling 12n (ratio - 1)
1 1.084438 1.0133
2 1.042207 1.0130
5 1.016784 1.0070
10 1.008365 1.0038
20 1.004175 1.0020
50 1.001668 1.0008
100 1.000834 1.0004
170 1.000490 1.0002
Taking the logarithm of Stirling's formula gives a sharper statement than :
The second term, about , is what keeps the ratio in the first table well below 1 for so long.
Consequences worth remembering:
- : the ratio is about , which tends to 0.
- for every constant : the factor eventually beats once .
- , as shown above.
Fibonacci numbers and the golden ratio
The Fibonacci numbers , , grow exponentially with base
the two roots of . The closed form is , and since the second term is smaller than in absolute value, so is simply rounded to the nearest integer. Hence . Fibonacci numbers bound the height of AVL trees and the number of steps of Euclid's algorithm. The closed form is derived in Linear Recurrences; here is a numerical check.
import math
phi = (1 + math.sqrt(5)) / 2
a, b = 0, 1
mismatches = 0
for i in range(71):
if round(phi**i / math.sqrt(5)) != a:
mismatches += 1
if i in (10, 20, 40, 70):
print(f"F_{i} = {a}, ratio F_(i+1)/F_i = {b / a:.10f}")
a, b = b, a + b
print("mismatches with round(phi^i / sqrt 5) for i <= 70:", mismatches)
print("phi =", round(phi, 10))F_10 = 55, ratio F_(i+1)/F_i = 1.6181818182
F_20 = 6765, ratio F_(i+1)/F_i = 1.6180339985
F_40 = 102334155, ratio F_(i+1)/F_i = 1.6180339887
F_70 = 190392490709135, ratio F_(i+1)/F_i = 1.6180339887
mismatches with round(phi^i / sqrt 5) for i <= 70: 0
phi = 1.6180339887
The ratio of consecutive Fibonacci numbers converges to , quickly. The check stops at because beyond that floating point no longer holds enough digits; exact big integers would be needed.
Functional iteration
Write for applied times: and . For example, with , . Do not confuse , the logarithm applied times, with , the -th power of the logarithm: , while .
The iterated logarithm
counts how many times you must take before the value drops to 1 or below. Each extra unit of needs a tower of twos one level higher:
| 1 | 0 |
| 2 | 1 |
| 3, 4 | 2 |
| 5 to 16 | 3 |
| 17 to 65536 | 4 |
| 65537 to | 5 |
has 19,729 decimal digits, far more than the roughly atoms in the observable universe. So for every input an algorithm will ever see, . It still tends to infinity, so it is not ; it is for any fixed number of logarithms.
import math
def lg_star(n):
count = 0
while n > 1:
n = math.log2(n) # exact for powers of two, works on huge ints
count += 1
return count
for n in [1, 2, 3, 4, 5, 16, 17, 65536, 65537, 2**65536]:
label = "2^65536" if n == 2**65536 else str(n)
print(f"lg*({label}) = {lg_star(n)}")
print("decimal digits of 2^65536:", math.floor(65536 * math.log10(2)) + 1)lg*(1) = 0
lg*(2) = 1
lg*(3) = 2
lg*(4) = 2
lg*(5) = 3
lg*(16) = 3
lg*(17) = 4
lg*(65536) = 4
lg*(65537) = 5
lg*(2^65536) = 5
decimal digits of 2^65536: 19729
Where does such a slow function come from? An algorithm that repeatedly replaces a problem of size by one of size runs for rounds. The union-find structure with union by rank and path compression, covered in the Data Structures course of this track, has an amortized cost per operation bounded by in one classic analysis and by the even slower inverse Ackermann function in the tight one.
Test yourself
What is ?
- 16
- 4
- 5
- 2
Which pair of crude bounds proves ?
Stirling's formula has relative error about . Roughly how far off is it at ?
- About 17 percent
- About 1.7 percent
- About 0.17 percent
- Exactly right
Which statement is false?