Logarithmic Growth and Scales
Logarithms grow very slowly: doubling the input adds only a fixed step to the output. That makes them perfect for two jobs: describing algorithms that stay fast as data grows, and drawing or measuring quantities that span many orders of magnitude, such as sound loudness, earthquake strength or request latencies.
Slow, slower, slowest
Compare how a few functions respond as grows by factors of ten:
import math
print(f"{'n':>13} {'log2 n':>7} {'sqrt n':>8} {'n':>13} {'n^2':>15}")
for k in [1, 3, 6, 9]:
n = 10 ** k
print(f"{n:>13,} {math.log2(n):7.1f} {math.sqrt(n):8.0f} {n:>13,} {n*n:>15.1e}") n log2 n sqrt n n n^2
10 3.3 3 10 1.0e+02
1,000 10.0 32 1,000 1.0e+06
1,000,000 19.9 1000 1,000,000 1.0e+12
1,000,000,000 29.9 31623 1,000,000,000 1.0e+18
From ten to a billion, only goes from about 3 to about 30. This is why an algorithm such as binary search feels instant on huge data, while becomes hopeless. Growth Rates and Big-O compares these classes in detail.
The key property: multiplying the input adds to the log. . Every doubling of the data costs binary search one more step.
Logarithmic scales
On an ordinary (linear) axis, equal distances mean equal differences: 0, 10, 20, 30. On a logarithmic axis, equal distances mean equal ratios: 1, 10, 100, 1000. Each step is "times ten" instead of "plus ten".
Log scales are the right choice when values span several orders of magnitude. Plot request latencies on a linear axis and the slow outliers squash everything else into a line at the bottom; on a log axis each order of magnitude gets the same room:
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(7)
latency_ms = rng.lognormal(mean=3.0, sigma=1.0, size=2000)
fig, (a, b) = plt.subplots(1, 2, figsize=(8, 3.2))
a.hist(latency_ms, bins=50)
a.set_title("linear x-axis")
a.set_xlabel("latency (ms)")
b.hist(latency_ms, bins=np.logspace(-0.5, 3, 50))
b.set_xscale("log")
b.set_title("log x-axis")
b.set_xlabel("latency (ms)")
fig.tight_layout()
print(f"min {latency_ms.min():.1f} ms, median {np.median(latency_ms):.1f} ms, max {latency_ms.max():.0f} ms")min 0.8 ms, median 18.9 ms, max 399 ms
Tip: Monitoring tools (Grafana, Prometheus histograms) often use exponentially growing bucket boundaries such as 1, 2, 5, 10, 20, 50, 100 ms for exactly this reason.
Decibels
Sound intensity varies over a factor of about between the quietest sound you can hear and a painful one. The decibel scale compresses that with a common log:
| Ratio | dB |
|---|---|
| 1 | 0 |
| 10 | 10 |
| 100 | 20 |
| 2 | about 3 |
| 120 |
So +10 dB means ten times the intensity, and +3 dB about double. Audio code uses the amplitude version, , because intensity grows with the square of amplitude (and the power law turns the square into the factor 2). A volume slider in a game or media player usually maps its position to decibels, then converts back to a gain factor:
import math
def db_to_gain(db):
return 10 ** (db / 20)
def gain_to_db(g):
return 20 * math.log10(g)
for db in [0, -6, -12, -20, -40, -60]:
print(f"{db:4d} dB -> gain {db_to_gain(db):.4f}")
print("half amplitude =", round(gain_to_db(0.5), 2), "dB") 0 dB -> gain 1.0000
-6 dB -> gain 0.5012
-12 dB -> gain 0.2512
-20 dB -> gain 0.1000
-40 dB -> gain 0.0100
-60 dB -> gain 0.0010
half amplitude = -6.02 dB
A linear slider (gain = position) sounds wrong because our ears hear ratios, not differences: most of the slider's travel would sound almost equally loud.
Other log scales
- Earthquake magnitude: each whole step is about 10 times the shaking amplitude and about 32 times the energy.
- pH in chemistry: , so pH 4 is ten times as acidic as pH 5.
- Musical pitch: each octave doubles the frequency; the 12 semitones of an octave each multiply it by .
- Star brightness (magnitudes) and camera exposure (f-stops) are log scales too.
Exercises
Exercise 1: Doubling the data
Binary search needs 17 steps on a list. About how many steps does it need on a list 8 times as long?
Answer
20 steps.
Solution
, so . Three more steps: .
Exercise 2: Decibel ratios
How many decibels correspond to an intensity ratio of 1000? And what intensity ratio does +30 dB plus +3 dB (33 dB) roughly mean?
Answer
30 dB; about 2000 times.
Solution
Exactly: .
Exercise 3: Log-spaced buckets
Write code that prints histogram bucket boundaries from 1 ms to 1000 ms where each boundary is twice the previous one. How many boundaries are there?
Answer
10 boundaries: 1, 2, 4, …, 512 (the next, 1024, is past 1000).
Solution
The boundaries are , because .
b, bounds = 1, []
while b <= 1000:
bounds.append(b)
b *= 2
print(len(bounds), bounds)10 [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
Exercise 4: Semitones
The note A4 is 440 Hz. Compute the frequency 12 semitones up and 7 semitones up (a "perfect fifth").
Answer
880 Hz and about 659.26 Hz.
Solution
Each semitone multiplies by , so semitones multiply by . 12 semitones: . 7 semitones: .
print(440 * 2 ** (12 / 12), round(440 * 2 ** (7 / 12), 2))880.0 659.26
Test yourself
On a logarithmic axis, equal distances represent equal…
- differences
- ratios
- sums
- squares
A sound goes from 50 dB to 70 dB. How has its intensity changed?
If the input of an algorithm grows from 1,000 to 1,000,000 items, its work roughly…
- doubles
- grows 1000 times
- stays exactly the same
- grows a million times