Comparing Growth Rates
The previous lessons built a toolbox: definitions, limits, and the standard functions with their rules. This lesson puts it to work on the most common task in algorithm analysis, deciding which of two running times grows faster. It shows the five classic growth rates side by side, sorts a list of fourteen functions with one trick (take logarithms), turns growth rates into "how large an input can I afford", and finds the crossover point where an asymptotically faster algorithm actually starts to win.
Watch them grow
The lab plots , , , and as grows. Press Play. On the linear scale the vertical axis stops at , so leaves the chart almost at once.
Switch the scale to logarithmic to see all five at once. On a log scale a polynomial becomes a curve that flattens out, while becomes a straight line that climbs at a constant rate.
The table gives the exact values the lab shows at a few input sizes. Doubling adds 1 to , doubles , a bit more than doubles , multiplies by 4 and squares .
import math
print(f"{'n':>4} {'lg n':>6} {'n':>4} {'n lg n':>7} {'n^2':>6} {'2^n':>22}")
for n in [8, 16, 32, 64]:
print(f"{n:>4} {math.log2(n):>6.0f} {n:>4} {n * math.log2(n):>7.0f} {n * n:>6} {2**n:>22,}") n lg n n n lg n n^2 2^n
8 3 8 24 64 256
16 4 16 64 256 65,536
32 5 32 160 1024 4,294,967,296
64 6 64 384 4096 18,446,744,073,709,551,616
Sorting functions by taking logarithms
To compare and when both are made of powers and exponentials, compare and instead. Logarithms turn exponents into factors, which are much easier to compare. The rule is:
- If , then , so .
- If stays bounded, the ratio stays bounded and the two are within constant factors of each other.
Note what the rule does not say. Comparing and only up to constant factors is too weak: , yet . It is the difference of the logarithms that has to be examined, not their ratio.
Some disguised functions become obvious once their logarithm is written down, with :
| Function | of it | So it equals |
|---|---|---|
| the constant 2 | ||
| , more than any polynomial | ||
| also more than any polynomial |
The program lists fourteen functions in increasing order, each through its logarithm as a formula in , and prints the gap between neighbours at , , and . A gap that keeps growing means the next function is strictly faster.
import math
lg = math.log2
LN2 = math.log(2)
# each function as lg f(n), written in terms of L = lg n
fns = [
("n^(1/lg n)", lambda L: 1.0),
("sqrt(lg n)", lambda L: 0.5 * lg(L)),
("lg n", lambda L: lg(L)),
("lg^2 n", lambda L: 2 * lg(L)),
("sqrt n", lambda L: L / 2),
("n", lambda L: L),
("lg(n!)", lambda L: lg(math.lgamma(2.0**L + 1) / LN2)),
("n lg n", lambda L: L + lg(L)),
("n^2", lambda L: 2 * L),
("(lg n)!", lambda L: math.lgamma(L + 1) / LN2),
("(lg n)^lg n", lambda L: L * lg(L)),
("2^n", lambda L: 2**L),
("n 2^n", lambda L: 2**L + L),
("n!", lambda L: math.lgamma(2.0**L + 1) / LN2),
]
Ls = [16, 64, 256, 512]
print("gap = lg f(next) - lg f(this), at n = 2^L")
print(f"{'f(n)':>12} -> {'next':<12}" + "".join(f"{'L=' + str(L):>12}" for L in Ls))
for (a, fa), (b, fb) in zip(fns, fns[1:]):
gaps = [fb(L) - fa(L) for L in Ls]
print(f"{a:>12} -> {b:<12}" + "".join(f"{g:12.3g}" for g in gaps))gap = lg f(next) - lg f(this), at n = 2^L
f(n) -> next L=16 L=64 L=256 L=512
n^(1/lg n) -> sqrt(lg n) 1 2 3 3.5
sqrt(lg n) -> lg n 2 3 4 4.5
lg n -> lg^2 n 4 6 8 9
lg^2 n -> sqrt n 0 20 112 238
sqrt n -> n 8 32 128 256
n -> lg(n!) 3.86 5.97 7.99 9
lg(n!) -> n lg n 0.136 0.0329 0.00815 0.00407
n lg n -> n^2 12 58 248 503
n^2 -> (lg n)! 12.3 168 1.17e+03 2.85e+03
(lg n)! -> (lg n)^lg n 19.7 88 364 733
(lg n)^lg n -> 2^n 6.55e+04 1.84e+19 1.16e+77 1.34e+154
2^n -> n 2^n 16 64 256 512
n 2^n -> n! 8.88e+05 1.14e+21 2.94e+79 6.83e+156
Every gap grows, with one exception: the gap from to shrinks toward 0, because the two are of each other (Factorials, Stirling and the Iterated Logarithm). Two more details are worth a look. The gap from to is 0 at : the two functions are equal there (), and only beyond it does pull away. And the first few gaps grow like , very slowly, but without bound, which is all that "strictly faster" requires.
The numbers are evidence, not proof. Each ordering is proved with the tools of Little o, Little omega and Limits: for example against means comparing with , an exponential against a polynomial in .
What an input budget buys
Growth rates become concrete when you fix a budget of steps and ask how large an input fits. Assume, as a model, a machine that does basic steps per second, and take budgets of a millisecond, a second and a day. The program finds the largest with for each budget by doubling and then binary search, counting nothing but the formula.
import math
def largest(f, budget):
# largest n >= 1 with f(n) <= budget, for an increasing f
hi = 1
while f(hi * 2) <= budget:
hi *= 2
lo, hi = hi, hi * 2 # f(lo) <= budget < f(hi)
while hi - lo > 1:
mid = (lo + hi) // 2
if f(mid) <= budget:
lo = mid
else:
hi = mid
return lo
fns = [
("n", lambda n: n),
("n lg n", lambda n: n * math.log2(n)),
("n^2", lambda n: n * n),
("n^3", lambda n: n**3),
("2^n", lambda n: 2**n),
("n!", lambda n: math.factorial(n)),
]
budgets = [("1 ms: 10^6", 10**6), ("1 s: 10^9", 10**9), ("1 day: 8.64e13", 864 * 10**11)]
print(f"{'f(n)':>8}" + "".join(f"{b:>20}" for b, _ in budgets))
for name, f in fns:
print(f"{name:>8}" + "".join(f"{largest(f, B):>20,}" for _, B in budgets)) f(n) 1 ms: 10^6 1 s: 10^9 1 day: 8.64e13
n 1,000,000 1,000,000,000 86,400,000,000,000
n lg n 62,746 39,620,077 2,110,372,739,876
n^2 1,000 31,622 9,295,160
n^3 100 1,000 44,208
2^n 19 29 46
n! 9 12 16
Two rows are missing because their answers are absurd: with steps, a second handles , and with steps it handles . The table shows the real meaning of the growth rates:
- For , a budget 86,400 times larger (a day instead of a second) buys an input 86,400 times larger. For it buys about 53,000 times more, because the logarithm grows too.
- For it buys only times more, and for about 44 times more.
- For a day buys 17 more items than a second, because each extra item doubles the cost. For it buys 4.
A faster computer is a bigger budget. If machines become 1,000 times faster (the step from the first column to the second), an algorithm handles inputs over 600 times larger, while a one handles 10 more items.
Crossover points
Asymptotics compare functions for large . For small the constants decide. Suppose algorithm A costs steps and algorithm B costs steps. B is cheaper while , and the program finds where that stops.
import math
a = lambda n: 100 * n * math.log2(n)
b = lambda n: n * n
last_b = max(n for n in range(2, 5000) if b(n) <= a(n))
print(f"n^2 <= 100 n lg n for 2 <= n <= {last_b}")
for n in [10, 100, last_b, last_b + 1, 10**4, 10**6]:
print(f" n = {n:>7}: 100 n lg n = {a(n):>16,.0f} n^2 = {b(n):>16,}")
small = [n for n in range(1, 50) if 2**n < n**3]
print(f"2^n < n^3 exactly for n = {small[0]}..{small[-1]}")n^2 <= 100 n lg n for 2 <= n <= 996
n = 10: 100 n lg n = 3,322 n^2 = 100
n = 100: 100 n lg n = 66,439 n^2 = 10,000
n = 996: 100 n lg n = 992,016 n^2 = 992,016
n = 997: 100 n lg n = 993,157 n^2 = 994,009
n = 10000: 100 n lg n = 13,287,712 n^2 = 100,000,000
n = 1000000: 100 n lg n = 1,993,156,857 n^2 = 1,000,000,000,000
2^n < n^3 exactly for n = 2..9
Up to the quadratic algorithm is cheaper, and at the two costs differ by less than one step. From on, the algorithm wins, and the gap grows quickly: at it is 500 times cheaper. Similarly an exponential algorithm beats an one for , then loses forever.
This is not just theory. Library sorts are hybrids for this reason: Python's built-in sort (Timsort) sorts short runs with binary insertion sort before merging them, and many quicksort implementations switch to insertion sort below a small cutoff. The asymptotically better algorithm takes over only where it is actually better.
Test yourself
Which function grows fastest?
. What can you conclude?
- Nothing about against : for example but
With a budget of steps, an algorithm handles . Roughly what does a budget of steps allow?
Algorithm A takes steps and B takes . Which is true?
- A is always faster because
- B is faster for and A from on
- B is always faster because 100 is a big constant
- They cross only at