The mathematics you will actually use
Averages, percentiles, sampling error, hash collisions, vectors, gradients and softmax, each worked by hand on hitcount’s own data.
This chapter lets you compute, and question, the numbers a service like hitcount produces, and read the notation of the AI Engineering pathway without stopping. None of it needs a degree. All of it repays working through small examples by hand, which is how this chapter presents it.
hitcount already produces numbers people act on. The sidebar shows an average reading time. The dashboard shows a p99 latency. The platform is considering counting only one hit in ten to save resources, and wants a “related posts” feature that suggests what to read next. Each of those is a piece of mathematics applied to hitcount’s own data, and each has a common way of being wrong.
What an average hides
Take ten posts from the blog with these view counts: 9,000, 600, 120, 80, 60, 50, 40, 30, 15 and 5. They add up to 10,000, so the mean is 1,000 views per post. Nine of the ten posts have fewer than 1,000 views, and eight have fewer than 150. The median, the middle value once they are sorted, is 55 (halfway between 50 and 60). The mean describes the total divided evenly; the median describes a typical post. Page views on almost any site look like this: a few pages take most of the traffic and a long tail shares the rest. In data shaped like that, the mean is pulled far from the typical value by the few largest ones.
Reading time has the same problem, from a different cause. Nine reports for one post, in seconds: 40, 45, 50, 55, 60, 65, 70, 80 and 28,800. The last is a reader who left the tab open for eight hours. The mean is 29,265 ÷ 9 ≈ 3,252 seconds, about 54 minutes, for a post that most people read in a minute. The median is 60 seconds. Capping each report at 30 minutes before averaging helps, but the mean is still about 4 minutes. For the sidebar’s “typical reading time”, the median is the right statistic.
The mean still has its uses, and it is not wrong, only answering a different question. For capacity planning, total = mean × count, so the mean is exactly what you want when estimating total bytes stored or total CPU used. The measure of spread around it is the standard deviation: the square root of the average squared distance from the mean. In skewed data it is dominated by the extremes too, which is a warning in itself.
Percentiles, and why you cannot average them
The performance chapter used percentiles; here is how they behave when combined. The platform runs hitcount on two machines for a while. Server A handled 9,900 requests last minute with a p99 of 5 ms. Server B handled 100 requests with a p99 of 500 ms, because it was stuck in the snapshot stall.
The dashboard shows the fleet’s p99 as the average of the two servers’ p99s, 252.5 ms. Is that the p99 of all 10,000 requests? If not, what is?
Show the worked answer
No. 252.5 ms is not the latency of any real request, and it is not a percentile of anything. The question cannot be answered from two percentiles alone, because a percentile throws away the information needed to combine it.
Suppose we had kept counts instead. Server A: 9,850 requests at 5 ms or less, and 50 between 5 and 10 ms. Server B: all 100 requests between 250 and 500 ms. Combined, the p99 is the 9,900th fastest of 10,000 requests. The first 9,850 are A’s fast ones, and ranks 9,851 to 9,900 are A’s 5 to 10 ms requests. So the fleet’s p99 is between 5 and 10 ms. Server B’s requests are exactly the slowest 1%, and they show up at p99.5 and above.
The practical answer is to record histograms, counts of requests in fixed latency buckets such as up to 1 ms, 2, 5, 10, 25, 50 ms and so on, rather than percentiles. Histograms from different servers or different minutes combine by adding the counts in each bucket, and any percentile can then be read from the combined counts. The cost is precision: a percentile read from a histogram is only known to within its bucket, so the buckets need to be finest around the values you care about, such as the latency target. Monitoring systems that store histograms do this for you; ones that store pre-computed percentiles cannot combine them correctly at all.
Sampling: how much error one in ten introduces
To save work at peak load, the platform proposes counting a random one in ten hits and multiplying each count by ten. Is the result right?
On average, yes. If each hit is kept with probability 0.1, the expected number kept from n hits is 0.1n, and multiplying by ten gives n. An estimate whose average equals the true value is called unbiased. The question that matters is how far a single estimate strays. The number of kept hits follows a binomial distribution, whose variance is n × p × (1 − p). For a post with 1,000 true views: the expected kept count is 100, the variance is 1,000 × 0.1 × 0.9 = 90, and the standard deviation is about 9.5. Multiplied by ten, the estimate is 1,000 give or take about 95, roughly 10%.
For a post with 50 views, the expected kept count is 5, the standard deviation about 2.1, and the estimate is 50 give or take about 21, more than 40%. A rule of thumb follows: the relative error is about 1 ÷ √k, where k is the number of samples actually kept. A hundred kept samples give about 10%; ten thousand give about 1%. So sampling is fine for the trending list, whose pages have tens of thousands of views, and poor for the long tail, where a blog owner checking their newest post would see numbers that jump around. The decision: sample only on the platform-wide trending computation, and keep exact counts per page.
Collisions: the birthday bound
Twice in this pathway hitcount replaced a string with a hash: 64-bit page IDs for the dashboard, and hashed IP-and-path pairs in the bot filter. Someone suggests saving memory with 32-bit hashes. How likely is it that two different keys get the same hash?
With 32-bit hashes there are about 4.3 billion possible values. The platform has 5 million pages. Roughly how many pairs of pages would share a hash?
Show the worked answer
There are n(n − 1)/2 pairs of pages, about n²/2, and each pair collides with probability 1/N, where N is the number of possible hash values. So the expected number of colliding pairs is about n² ÷ 2N. With n = 5 million and N = 2³² ≈ 4.3 × 10⁹, that is 2.5 × 10¹³ ÷ 8.6 × 10⁹ ≈ 2,900. Nearly three thousand pairs of pages would be merged into one counter each.
For the original blog, n = 2,000: 4 × 10⁶ ÷ 8.6 × 10⁹ ≈ 0.0005, about a 1 in 2,000 chance of any collision at all. With 64-bit hashes and 5 million pages: 2.5 × 10¹³ ÷ 3.7 × 10¹⁹ ≈ 7 × 10⁻⁷. The size that is safe depends on n squared, not n, which is why it surprises people. This is the same arithmetic as the birthday problem, where 23 people are enough for an even chance that two share a birthday.
Vectors: deciding which posts are related
For “related posts”, each post is represented as a vector, a list of numbers. In practice a model turns each post’s text into a vector of a few hundred numbers, called an embedding, arranged during the model’s training so that posts about similar things point in similar directions. To see the arithmetic, use three dimensions and pretend they mean something readable: how much a post is about Go, about concurrency, and about food.
Post A, on Go’s mutexes, is [0.9, 0.8, 0.1]. Post B, on goroutine leaks, is [0.8, 0.9, 0.2]. Post C, on cafés in Lisbon, is [0.1, 0.1, 0.9]. The dot product multiplies matching entries and adds them up. A · B = 0.72 + 0.72 + 0.02 = 1.46. The length of a vector is the square root of its dot product with itself: |A| = √1.46 ≈ 1.208, and |B| = √1.49 ≈ 1.221. Cosine similarity divides the dot product by both lengths, which removes the effect of size and leaves only direction: 1.46 ÷ (1.208 × 1.221) ≈ 0.99. For A and C, the dot product is 0.09 + 0.08 + 0.09 = 0.26, |C| = √0.83 ≈ 0.911, and the cosine is 0.26 ÷ (1.208 × 0.911) ≈ 0.24. Post B is related to A; post C is not. Real embedding dimensions do not have readable meanings, but the arithmetic is identical.
To score one post against every other, stack all the post vectors as the rows of a matrix E, with n rows and d columns, and multiply it by the query vector q. Each entry of the result is one row’s dot product with q. The shapes follow a rule worth memorising: an (n × d) matrix times a (d × 1) vector gives an (n × 1) result; the inner dimensions must match, and they are the ones summed away. For one blog, n = 2,000 posts and d = 768: 1.5 million multiply-adds and 6 MB of data, well under a millisecond.
For the platform, n = 5 million: 3.8 billion multiply-adds per query, and E is 5 million × 768 × 4 bytes ≈ 15 GB, more than our machine’s entire memory. Even with enough RAM, streaming 15 GB at memory bandwidth takes around a second per query. The machine chapter’s cost model applies to linear algebra like everything else. This is why systems for searching vectors at scale use approximate indexes that look at a small fraction of the rows, a topic in the AI Engineering pathway, and why ML hardware processes many queries at once: multiplying E by a matrix of many query vectors reuses each row of E for all of them while it is in cache. A layer of a neural network is the same operation, a matrix of learned weights multiplied by a batch of input vectors, followed by a simple non-linear function.
Gradients: fitting a trend by walking downhill
The platform wants to predict tomorrow’s views for a rising post. The simplest model is a straight line: predicted views = w × day + b. Training means choosing w and b so the predictions match past data. Take three days of data, in hundreds of views: day 1 had 2, day 2 had 4, day 3 had 6.
First, a measure of wrongness, the loss: the mean of the squared errors. Start with w = 0 and b = 0. Every prediction is 0, the errors (prediction minus actual) are −2, −4 and −6, and the loss is (4 + 16 + 36) ÷ 3 ≈ 18.7. The gradient says how the loss changes as each parameter changes. For this loss, the derivative with respect to w is (2/n) × Σ error × day = (2/3) × (−2 − 8 − 18) ≈ −18.7, and with respect to b it is (2/n) × Σ error = (2/3) × (−12) = −8. Both are negative, meaning that increasing w and b would reduce the loss.
Gradient descent takes a step in the downhill direction, scaled by a learning rate. With a learning rate of 0.05: w becomes 0 + 0.05 × 18.7 ≈ 0.93, and b becomes 0 + 0.05 × 8 = 0.4. The new predictions are 1.33, 2.27 and 3.2, the errors are −0.67, −1.73 and −2.8, and the loss is about 3.8, down from 18.7. Repeating the step converges on w = 2, b = 0, which fits the data exactly.
Now change one variable: a learning rate of 0.5. The first step sets w ≈ 9.3 and b = 4, the predictions become 13.3, 22.7 and 32, and the loss jumps to about 384. The step was so large it went past the bottom of the valley and up the other side, and the next step will overshoot further. Most training problems you will read about, a loss that explodes or one that stops improving, come down to step size.
In a neural network the loss depends on a parameter through many layers. The chain rule of calculus says that the derivative through a chain of functions is the product of each link’s derivative. Backpropagation is the chain rule applied systematically from the loss backwards through every layer, so that one pass gives the gradient for every parameter. You need the picture and the chain rule; nobody will ask you to integrate anything.
Probabilities: choosing which related post to show
The related-posts feature produces a score for each candidate post. Suppose three candidates score 2, 1 and 0. Always showing the top one means the other two never get a chance to prove themselves, so we want to choose randomly, favouring higher scores. Softmax turns scores into probabilities: raise e to each score and divide by the total. e² ≈ 7.39, e¹ ≈ 2.72, e⁰ = 1, total 11.11, so the probabilities are about 0.67, 0.24 and 0.09.
Temperature divides the scores before the softmax. At a temperature of 0.5 the scores become 4, 2 and 0, and the probabilities about 0.87, 0.12 and 0.02: much more concentrated on the favourite. At a temperature of 2 they become 1, 0.5 and 0, giving about 0.51, 0.31 and 0.19: much more even. A language model does exactly this at every step, over a vocabulary of tens of thousands of tokens, which is why the same prompt can produce different answers and why the temperature setting changes how predictable they are.
Training such a model means making the observed data as probable as possible. If the data is a thousand observed choices, each given probability 0.01 by the model, the probability of all of them is 0.01 multiplied by itself a thousand times, which is 10⁻²⁰⁰⁰. The smallest positive float64 is around 10⁻³⁰⁸, so that product underflows to exactly zero, a representation edge of the kind the second chapter described. Taking logarithms turns the product into a sum, 1,000 × ln(0.01) ≈ −4,605, which is easy to store. That is why training objectives are written as log-likelihoods.
How much mathematics is enough
| Question about hitcount | Tool | What getting it wrong looks like |
|---|---|---|
| What is a typical post’s reading time? | median, not mean | “54 minutes” for a one-minute read |
| What is the fleet’s p99? | merged histograms | an average of percentiles that matches no request |
| Can we count one hit in ten? | binomial error, about 1/√k | small pages with ±40% counts |
| Is a 32-bit hash big enough? | birthday bound, n²/2N | thousands of merged pages |
| Which posts are related? | cosine similarity, matrix shapes | a 15 GB scan per query |
| Where are views heading? | loss, gradient, learning rate | a model whose loss explodes |
| Which post do we suggest? | softmax, temperature, log-likelihood | always the same suggestion, or a product that underflows |
That table is the level to aim for: enough to compute each answer by hand on a small example. Resist a detour into proofs before something concrete needs them. When an AI Engineering chapter uses an idea you cannot work through on three numbers, come back to the linked book for that idea, and only that one. The 3Blue1Brown series on linear algebra builds the geometric picture behind vectors and matrices in an evening, and is a good place to start if this chapter’s section on vectors felt quick.
That completes the foundations. hitcount has gone from source to process, from bytes to meaning, through caches, the kernel, concurrent requests, the network, an estimate, a profile, its runtime and its own statistics. One assumption has held throughout: hitcount runs on one machine, and that machine either works or does not. The next pathway, Distributed Systems, removes it. Put hitcount on three machines so that one can fail, and a new question appears that nothing in this pathway can answer: when the machines disagree about a page’s count, which one is right?
Free PDF. Exactly the subset of maths ML needs, without a full undergraduate detour.
Builds the geometric intuition first. Watch before, or alongside, any formal treatment.