TExcelTAD
Home › NumPy › Zipf Distribution

Zipf Distribution

Zipf's law says that in many collections, the k-th most common item appears about 1/k as often as the most common one. The linguist George Zipf observed it in word frequencies: in English text, "the" is the most frequent word, "of" appears about half as often, "and" about a third as often, and so on.

The same pattern shows up in city sizes, website traffic, the popularity of songs and the number of downloads of software packages.

Parameter Meaning
a exponent (must be > 1). Larger a makes the top ranks even more dominant
size output shape

Generating Zipf data

rng.zipf(a) returns positive integers 1, 2, 3, …. Value k has probability proportional to 1 / k^a, so 1 is the most frequent, 2 the next, and very large values are rare but possible:

python · try it yourself
import numpy as np

rng = np.random.default_rng(42)
print(rng.zipf(a=2, size=15))
[4 1 1 1 1 2 4 4 1 1 1 1 1 1 1]

Most values are 1, with a few 2s and 4s. In larger samples a very big number appears now and then (the next example draws one above 100,000): that is the long tail.

Checking the 1/k pattern

Count how often each value appears and compare with the frequency of 1. With a = 2, value k should appear 1/k² as often as value 1:

python · try it yourself
import numpy as np

rng = np.random.default_rng(42)
x = rng.zipf(a=2, size=500_000)
counts = np.bincount(x[x <= 6])                  # counts for values 0..6 (0 never occurs)
for k in range(1, 7):
    print(f"k={k}: ratio to k=1 is {counts[k] / counts[1]:.4f}   (theory {1 / k**2:.4f})")
print("largest value drawn:", x.max())
k=1: ratio to k=1 is 1.0000   (theory 1.0000)
k=2: ratio to k=1 is 0.2484   (theory 0.2500)
k=3: ratio to k=1 is 0.1110   (theory 0.1111)
k=4: ratio to k=1 is 0.0624   (theory 0.0625)
k=5: ratio to k=1 is 0.0397   (theory 0.0400)
k=6: ratio to k=1 is 0.0277   (theory 0.0278)
largest value drawn: 136359

Note x[x <= 6] before np.bincount: because the tail is so long, the largest value can be huge, and counting every possible value up to it would waste a lot of memory.

Simulating word frequencies

Give each rank a word and draw a "text" of 1,000 words. The most common word dominates, exactly like real language:

python · try it yourself
import numpy as np

rng = np.random.default_rng(5)
vocab = np.array(["the", "of", "and", "to", "a", "in", "is", "it"])
ranks = rng.zipf(a=1.8, size=1000)
ranks = ranks[ranks <= len(vocab)]               # keep words we have in the vocabulary
words = vocab[ranks - 1]

values, counts = np.unique(words, return_counts=True)
order = np.argsort(counts)[::-1]
for w, c in zip(values[order], counts[order]):
    print(f"{w:4} {c:4d} {'*' * (c // 20)}")
the   517 *************************
of    162 ********
and    71 ***
to     37 *
a      37 *
in     22 *
is     19
it     13

Visualising on log-log axes

Plotted on logarithmic axes, a Zipf distribution is a straight line with slope −a. That straight-line test is how Zipf's law is checked on real data:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(42)
plt.figure(figsize=(6, 3.5))
for a, color in [(1.5, "#e07a5f"), (2, "#4dabcf"), (3, "#81b29a")]:
    x = rng.zipf(a, 200_000)
    counts = np.bincount(x[x <= 50])[1:]           # frequencies of 1..50
    k = np.arange(1, len(counts) + 1)
    keep = counts > 0
    plt.loglog(k[keep], counts[keep] / x.size, "o", markersize=3, color=color, label=f"a = {a}")
plt.xlabel("rank k")
plt.ylabel("frequency")
plt.legend()
plt.tight_layout()
plt.show()
print("Plotted Zipf frequencies for a = 1.5, 2 and 3 on log-log axes")
Plotted Zipf frequencies for a = 1.5, 2 and 3 on log-log axes

Each set of points forms an approximately straight line; a larger a gives a steeper line (the top ranks take an even bigger share).

Note: NumPy requires a > 1, because for smaller exponents the probabilities 1/k^a would not add up to a finite total over infinitely many values.

Test yourself

According to Zipf's law (a = 1), how often does the 4th most common word appear compared with the most common?

  1. 4 times as often
  2. About 1/4 as often
  3. About 1/16 as often
  4. Equally often

Which values can rng.zipf(2) return?

  1. Floats between 0 and 1
  2. Positive integers 1, 2, 3, ...
  3. Integers from 0 to 2
  4. Negative integers

What does a Zipf distribution look like on log-log axes?

  1. A bell curve
  2. Approximately a straight line
  3. A circle
  4. A flat line