ch13 · Monte Carlo
Builds on ch12.
The question
The sizing model has produced a host count. How sure are we?
ch12 took a stated workload, multiplied along three chains, took the largest of the three answers, and produced a number. Every step was arithmetic you could check by hand. The number is correct. Whether it is right is a different question. Every input to that chain was itself uncertain, and the chain has no way to say so.
This chapter builds the machinery for asking the second question. It assumes you can read code and do arithmetic. It assumes nothing about statistics.
The material
A single number is a bet you did not know you placed
The table below is the book’s finished web service model: ch12’s host count, with the costs later chapters add to it.
| Output | Point estimate | 90% interval | Unit |
|---|---|---|---|
| hosts the model recommends | 54 | 20 to 230 | host |
| hosts in the fleet | 54 | fixed | host |
| total cost of ownership | $2,002,083 | $1,508,230 to $2,923,724 | USD |
| cost per million requests | $1.82 | $0.55 to $5.98 | USD/megarequest |
| cost per stored TB per month | $839.64 | $305.33 to $2,108 | USD / TB / month |
| capex | $421,214 | $272,130 to $658,773 | USD |
| annual opex | $316,174 | $227,660 to $484,257 | USD / year |
| annual energy | 206,269 | 159,636 to 269,269 | kWh / year |
| utilisation at the busy hour | 0.644 | 0.156 to 2.48 | |
| utilisation with one host down | 0.656 | 0.159 to 2.53 | |
| working set against memory | 0.746 | 0.194 to 2.67 | |
| disk fill at horizon | 0.670 | 0.213 to 2.12 | |
| fraction of the fleet doing nothing useful | 0.321 | 0.213 to 0.457 | |
| utilisation, counting coordination | 0.948 | 0.233 to 3.81 | |
| utilisation | 0.644 | 0.156 to 2.48 | |
| residence time | 0.0367 | 0.0128 to 0.857 | second |
| time spent queueing | 0.0236 | 0.0021 to 0.839 | second |
| requests in the system | 1,562 | 160 to 107,336 | request |
| requests in flight, if none waited | 556 | 135 to 2,147 | request |
| how much the queueing view understated it | 1.47 | 1.27 to 1.84 | |
| fraction of the peak already built | 0.328 | 0.186 to 0.584 |
Source — web_service-reference · the model to explore; each input with a range has a slider
The Point estimate column shows what you get when you work the model out once, with every input at the middle of its declared range. The 90% interval column shows what happens when you work the model out many times, letting each input be as uncertain as the person who wrote it down is. This column holds the middle nine answers in ten.
Look at the host count row. The point estimate is a correctly computed number. Its range stretches wide: the top is many times the bottom, and the point estimate sits nearer the bottom than the middle. Nothing went wrong. The calculation had no way to say that its inputs were uncertain, so it did not say it.
The finished model draws more uncertain inputs than ch12’s, from the same seed. So each input receives different random values, and the host range can differ from ch12’s in its last digit.
The chart shows the host count’s answers as bars. Each bar counts how many answers landed in that stretch of host counts. The solid red line marked point is the point estimate. The dashed lines marked p5 and p95 are the two ends of the range. The heading says how many times the model was worked out. The median in the subtitle is the middle answer, with half the answers below it. The words sample, interval and the p in p5 are defined in the sections below, where the method needs them.
The rest of the chapter is how the 90% interval column was produced.
Instead of one value, a bag of values
If you do not know what the growth rate will be, do not give the model one growth rate. Give it a bag of plausible growth rates and work the model out once for every value. You get a bag of answers, and that bag is the answer.
When several inputs are uncertain, each has its own bag. Each time through the model, you draw one value from every bag, with each input drawn separately from the others. If two inputs were drawn together, they would rise and fall together. That is a different claim about the world from two inputs that vary on their own.
That is Monte Carlo. Everything else is bookkeeping: how to fill each bag and how to read the bag of answers.
Two words: the bag of plausible values for an input is its distribution, and one value drawn from the bag is a sample. The bag of answers is the output’s distribution.
Two more words arrive later in this chapter, each where the method needs them.
Where the bag comes from
Filling a bag takes two lines of code, and the same two lines work for every shape.
Every shape can be described by one function that answers one question: given a fraction between zero and one, what value is that fraction of the bag below? Give it one half and it returns the middle value. Give it nine tenths and it returns the value nine tenths of the bag is below.
The value it returns is a percentile: the value a given fraction of the bag is below.
So the
function turns a fraction into a percentile. The book calls it the shape’s percentile function.
In the code it is called ppf.
Pick a fraction at random between zero and one, every fraction equally likely, and ask the percentile function for the value there. Do that as many times as the model’s scenario asks. The heading of each chart on this page says how many. The values you get are samples from the distribution: they fill the bag.
def sample(spec: dict, n: int, generator: np.random.Generator) -> np.ndarray:
"""Draw ``n`` values from a declared distribution.
Two lines, and they are the chapter's whole sampling idea. The first finds the shape the
declaration names and its parameters. The second draws ``n`` random fractions between 0 and 1
and hands them to that shape's percentile function, which returns the value at each.
"""
shape, parameters = one_shape(spec)
return SHAPES[shape](generator.random(n), **parameters)
generator.random(n) draws the random fractions. The percentile function turns them into values.
That is the whole sampler. That is why adding a shape to this book is three lines of code rather
than a new dependency.
The technique is called inverse transform sampling. Any shape whose percentile function you can write down, you can sample. Problem 13.1 asks you to write one.
Here is the simplest:
def uniform_ppf(u: np.ndarray, minimum: float, maximum: float) -> np.ndarray:
"""Every value between two bounds, equally likely.
Honest when the bounds are genuinely all you know — a contract that caps a price, a retention
window somebody will choose from a range. Dishonest as a default, because it says the bounds
are as likely as the middle, and almost nothing real is like that.
"""
if not minimum <= maximum:
raise ValueError(f"uniform needs minimum <= maximum, got {minimum}, {maximum}")
return minimum + u * (maximum - minimum)
A fraction of zero gives the minimum, a fraction of one gives the maximum, and the values between lie on a straight line. You could have guessed that one. The next one needs a picture.
def triangular_ppf(u: np.ndarray, minimum: float, likely: float, maximum: float) -> np.ndarray:
"""An expert's guess: the least it could be, the most, and the one they would bet on.
The shape most sizing inputs arrive in, because it is the shape of the answer to "what is it,
roughly?". Its flaw is worth stating every time it is used: it asserts that nothing outside
the bounds can happen, and the bounds came from somebody's memory.
The two branches meet at the mode. Below it the area grows as the square of the distance from
the minimum, which inverts to a square root — the whole derivation, and problem 13.1 asks for
it again for a distribution that is not here.
"""
if not minimum <= likely <= maximum:
raise ValueError(
f"triangular needs min <= likely <= max, got {minimum}, {likely}, {maximum}"
)
if maximum == minimum:
return np.full_like(u, minimum)
width = maximum - minimum
at_mode = (likely - minimum) / width
below = minimum + np.sqrt(u * width * (likely - minimum))
above = maximum - np.sqrt((1.0 - u) * width * (maximum - likely))
return np.where(u < at_mode, below, above)
Picture the triangle. Its base runs from the least value the input could take to the most. Its peak
stands over the value the expert would bet on: the most likely value, which the code calls
likely. This value is called the mode.
The height of the triangle at a value says how likely values near it are. A shape drawn this way (higher where values are likely, lower where they are not) is the input’s density. The whole area under it is one.
The area under the density from the minimum up to a value is the fraction of the bag below that value. So finding the value for a fraction means finding where the area from the left edge reaches that fraction.
Left of the peak, the area up to a value is a smaller triangle. Its width and its height both grow in step with the distance from the minimum. So its area grows as the square of that distance. Halfway from the minimum to the peak, the small triangle is half as wide and half as tall, so it holds a quarter of the area it holds at the peak.
Set that area equal to the fraction and solve for the value: you take a square root. That is the
line below in the code.
Right of the peak, run the same argument from the maximum, using the area above the value. That is
the line above.
at_mode is the share of the whole area that lies left of the peak. The code uses below when the
fraction is smaller than that, and above otherwise.
Work it through on paper once. Problem 13.1 is the same exercise for a shape this book does not have, and it needs one integral.
Which shape for which input
Choosing a shape is a judgement, not a technical question. It is a claim about the world, and the first claim a reviewer should argue with.
Lognormal, for prices and growth and anything that compounds. The docstring that follows says why it is the right shape for those things and explains why it is declared by two values rather than by a mean.
def lognormal_ppf(u: np.ndarray, p10: float, p90: float) -> np.ndarray:
"""Multiplicative uncertainty: the shape of prices, growth rates and anything compounding.
Parameterised by two percentiles rather than by the mean and standard deviation of the
logarithm, because nobody has an intuition for the second and everybody has one for the first.
"I would be surprised if it were under 11 or over 19" is a sentence a person can say about a
price, and it is exactly ``p10=11, p90=19``.
Two properties earn it its place. It cannot go negative, and neither can a price. And a
product of several of them is another one, which is what a chain of multiplications in a
sizing model *is* — so the uncertainty that arrives at the end of the chain has this shape
whether or not anybody chose it.
"""
if not 0 < p10 < p90:
raise ValueError(f"lognormal needs 0 < p10 < p90, got p10={p10}, p90={p90}")
# Solve for the two parameters of the underlying normal from the two stated percentiles.
log_median = (np.log(p10) + np.log(p90)) / 2.0
log_spread = (np.log(p90) - np.log(p10)) / (2.0 * Z90)
return np.exp(log_median + log_spread * normal_ppf(u))
The code uses normal_ppf and Z90. The first is the normal shape’s percentile function, imported
from sizing/normal.py. The second is normal_ppf(0.9), defined at the top of sizing/mc.py: how
far the 90th percentile of a standard normal sits from its middle. Problem 13.2 needs both.
Triangular, for an expert’s guess. The previous section shows you the code and explains when it is honest and what its flaw is.
Uniform, when the bounds are all you know. The previous section shows when this shape is honest and why it is dishonest as a default.
Normal, for measurement error. In this book it means one thing: the standard error beside a measured constant. A number was measured, the measurement wobbles, and it is as likely to wobble high as low. It is the wrong default for a price: a normal can go negative, and a price cannot. Appendix C gives each of the four shapes its own section, and then a Choosing section with a table and five questions for selecting one.
Choosing badly is not a rounding error. It is a claim about what can happen, made in a model file that will outlive the meeting it came from.
Only the inputs the model samples have a shape; the rest are single values, such as definitions, spec-sheet figures, margins, and decisions about fleet size. For every sampled input, the build refuses a source that does not name its shape.
| Input | Provenance | Source | |
|---|---|---|---|
| ○ | annual growth factorannual_growth | assumption | ch04 — lognormal because growth compounds and the factor cannot be zero or less. One future in ten grows by less than 12% a year, and one in ten by more than 60%; outside that range you would be surprised. One factor for requests and for records, because users drive both. It is a share a year, not an amount, which is the model’s assumption about how this service grows. |
| ○ | cache margincache_margin | assumption | ch08 — how much of the fleet’s memory is kept free of the working set, for its own daily swing and for the process heaps. Declared once, the ceiling on the working set checks against it (ch08), and from ch10 so does the chain that sizes the fleet for memory, so the two cannot drift apart. |
| ○ | contentioncontention | assumption | ch07 — an assumption: it has not been fitted for this service; a fit from throughput measured at three fleet sizes, one a single host, would replace it. Triangular, because a fit gives a central value and a range rather than a shape. Its maximum is the end to distrust: a serial fraction can always be worse than the one you measured. |
| ◐ | cores per hostcores_per_host | vendor claim | spec sheet: physical cores. A hyperthread is not a core, and a sheet that counts threads doubles this number without doubling the work a host does |
| ○ | crosstalkcrosstalk | assumption | ch07 — an assumption, not fitted for this service, though the same measurement as contention’s would replace it: a fit from throughput at three fleet sizes, one a single host. It is the harder of the two to fit because it shows only in how the curve bends at larger fleets, and the three measured sizes usually sit at the small end. Lognormal, because it is wide and cannot be negative, and because a shape should not assert a hard upper limit on a quantity this weakly known. |
| ○ | disk margindisk_margin | assumption | ch11 — room to re-replicate a dead host’s records onto the survivors, plus what a filesystem needs to keep allocating well. Declared once and used by the chain and by the ceiling |
| ◐ | disk per hostdisk_per_host | vendor claim | spec sheet: one local drive. Decimal TB, not TiB — appendix D, and it is a 10% difference |
| ○ | electricity priceelectricity_price | assumption | all-in delivered rate including transmission. Lognormal: it cannot go negative and its history is multiplicative |
| ○ | fully loaded salaryfully_loaded_salary | assumption | salary, employer costs, tooling and overhead. Lognormal because pay is right-skewed and cannot go negative; the p90 is a senior engineer in an expensive city |
| ○ | horizonhorizon | assumption | the refresh cycle this fleet is bought against |
| ◐ | host powerhost_power | vendor claim | typical draw under load, per host as configured. Triangular, and one of the few inputs here whose bounds are physical rather than editorial: a host cannot draw less than it idles at, or more than its supply will give it |
| ◐ | host pricehost_price | vendor claim | chassis, CPU, memory, drives and boot media, as configured. Lognormal like any price, and wide because a host is a configuration rather than a commodity |
| ○ | hosts in the fleethosts | assumption | The sizing decision, taken the usual way: the host count the model recommends (from ch10), worked out with every input at its point estimate. Change this number and watch the ceilings move; that is ch12’s exercise. |
| ○ | share of records touched in a busy hourhot_fraction | assumption | ch08 — the working set as a share of everything held. Triangular; nobody measures this and everybody has an opinion, and the maximum is a service whose users all look at the same week’s data |
| ● | hours per yearhours_per_year | fact | by definition, 365.25 x 24. The quarter-day is six hours a year; leaving it out would understate every hourly cost by under a tenth of a per cent—the same share every year, not growing with the horizon. It is smaller than this model’s other errors, and free to get right. |
| ○ | index overheadindex_overhead | assumption | indexes, the write-ahead log and journals as a multiplier on stored bytes. Triangular, and the bounds are for a service with a few indexes per table — a search-heavy one is off the top of this range |
| ◐ | licence per corelicence_per_core | vendor claim | the platform software’s per-core licence, as quoted. Lognormal: a price, and a wide one, because it is the line item most often negotiated. It is what makes the core count a cost as well as a capacity (ch15) |
| ◐ | licence per hostlicence_per_host | vendor claim | The design the plan was built on is licensed per core, with no per-host charge. When a design licenses per host, that figure goes here and zero in licence_per_core, allowing the two to be compared like for like. |
| ○ | one-off cost of moving to this designmigration_cost | assumption | The design the plan was built on runs on that platform already, so there is nothing to migrate. A challenger’s scenario overrides this with the team’s own estimate of the move, marked as an assumption. |
| ○ | network price per hostnetwork_price_per_host | assumption | switch ports, optics and cabling, amortised per host. Triangular rather than lognormal, although it is a price: it is a bill of materials divided by a host count somebody chose, so the bounds are the plausible designs rather than a market |
| ● | one coreone_core | fact | definition |
| ● | one hostone_host | fact | definition |
| ● | one requestone_request | fact | definition |
| ● | one yearone_year | fact | definition |
| ○ | os reserveos_reserve | assumption | the share of memory the kernel, the agents and the page cache floor keep before the service sees any. Triangular: a floor, a usual figure, and a host with too many agents on it |
| ○ | peak request rate, day onepeak_request_rate_t0 | assumption | ch04 — the busy hour, not the daily mean. Triangular, because this is an engineer’s lowest, most likely and highest values; claiming more precision would be invention. |
| ○ | peak-to-mean ratiopeak_to_mean | assumption | ch04 — the busy hour against the daily mean. Triangular, and it is a property of your traffic that belongs to the estate target: nothing here can measure it |
| ○ | PUEpue | assumption | ch16 — facility overhead. A multiplier on IT load, and the single number a colocation contract is most likely to disagree with you about. Triangular: the minimum is a good building, the maximum is a poor one, and below one is impossible |
| ○ | queueing marginqueueing_margin | assumption | ch06 — the share of the fleet kept idle at the busy hour. The ceiling lets utilisation go up to one minus this margin, and no further. Declared once, it is used by the ceiling that checks utilisation at the busy hour (ch06), the ceiling on utilisation counting coordination (ch07), the chain that sizes the fleet for requests (from ch10) and the ceiling with one host lost (ch11), so they cannot drift apart. |
| ◐ | ram per hostram_per_host | vendor claim | spec sheet: the modules fitted. The sheet says 64 GB and means GiB — appendix D — and the operating system will report less than either, which is os_reserve’s job |
| ○ | replication factorreplication_factor | assumption | three copies of every record, so that a host can die and take its disks with it. A different durability scheme substitutes its own factor here and the rest of the model is unchanged, which is the point of it being a node |
| ● | seconds per yearseconds_per_year | fact | by definition, 365.25 x 86,400 |
| ○ | CPU time per requestservice_demand | assumption | The lowest, likeliest and highest values are this book’s own choice for the running example: not measured on any machine, not taken from any product. It is held as an assumption because no reference machine is declared in rig/machine.yml; make measure-rig on a declared machine replaces it with a measured one. It is triangular, with three values, because it has not been measured. Once it is, it becomes a normal spread around the measurement, which is a change of claim and not only of numbers (ch13). |
| ○ | engineers, full-time equivalentstaff_fte | assumption | Engineers this fleet occupies, full-time equivalent. Triangular, and the shape cannot express what happens: people are not divisible, so the real spread moves in whole people. |
| ○ | records held, day onestored_data_t0 | assumption | The service owners estimate what the service holds today: its database and the objects users have uploaded, before replication, indexes or compression. It has not been counted yet, and counting it would turn the estimate into a fact. |
| ◐ | support ratesupport_rate | vendor claim | annual support as a fraction of capital cost. Triangular because it is negotiated inside a band the market sets rather than drawn from one: the spread is what different buyers get, not what varies from year to year |
| ○ | utilisation the model will admit toutilisation_cap | assumption | where this model stops being about queues (ch06) |
| 37 inputs | 6 facts, 8 vendor claims, 23 assumptions |
Source — web_service-reference · the model to explore; each input with a range has a slider
The table lists every input and its provenance. For a sampled input, the source names its shape, and most also say why that shape was chosen. The tally at the bottom shows what the model rests on: how many inputs trace to a source that can be checked (fact), how many come from a vendor’s sales material (vendor claim), and how many were decided by the modeller (assumption).
Running the bag through the model
Nothing changes about the arithmetic. The model is a graph of quantities, each computed from the
ones before it. Working it out at a point walks the graph in order, doing arithmetic on single
numbers. Sampling it walks the same graph in the same order, doing the same arithmetic on arrays:
one value per sample. The operation a * b means the same thing whether a and b are two numbers
or two long arrays.
So uncertainty travels through the graph without extra work. An input with a distribution becomes an array. Everything downstream of it becomes an array. A quantity with nothing uncertain upstream stays a single number, and the arithmetic uses that one number against every value in the array.
Every node in the graph has its own bag of values once the model has been sampled, not only the outputs at the end. Open the web service model and click any box in the graph. The panel beside the graph shows that node’s values as a bar chart, with its p5, median and p95 beneath it. Use it to find where the range of answers got wide: start at an input and click along the chain towards the output until the bar charts stop being narrow.
Reading the answer
An interval is the gap between two percentiles. This book reports the gap between the 5th and the 95th percentile, and calls it the 90% interval. On the charts they are the dashed lines p5 and p95. The book does not call it a confidence interval. That phrase means something precise to a statistician and something vaguer to most readers. What is meant here is the plain reading: the model put nine tenths of its belief in this range.
Why two percentiles rather than the smallest and the largest answer in the bag: the ends are properties of how many answers you collected, not of the model. Collect ten times as many and the largest gets larger, every time, because the unlucky combinations had more chances to turn up. The middle settles, and ch14 measures how quickly.
The red line marked point is the five-year total at the point estimate: every input at the middle of its range, the value half its bag is below. On this chart it sits below the median.
This is not a quirk of these numbers. Pass one uncertain input straight through, and the point is the middle answer exactly: the middle input gives the middle output. Multiply two uncertain inputs, and the point stays close to the middle. The staff cost, engineers times salary, is an example.
The five-year total adds several cost lines. Each line’s bag is lopsided: a short way down to its lowest values, a long tail up to its highest. That shape is called skewed. Each line’s own point sits at its own middle. Add the lines up. A line that comes in high can be far above its middle; a line that comes in low can be only a little below it. The highs outweigh the lows, so the middle of the total sits above the sum of the lines’ middles. The point estimate of the total is the sum of the lines’ points, which sit at their middles, so the point sits below the median of the chart.
The host count’s point also sits low, for a different reason: the model takes the largest of three chains. ch12 showed why that step pulls the point below the middle.
So the point estimate is not the middle answer once a model adds lopsided quantities or takes the largest of several.
How often each ceiling is breached
This is the ceiling table from ch12, for the finished model: the same fleet against the same ceilings. ch12 read its Verdict column, which is the plan at the point estimate.
| Ceiling | At the plan | Headroom | Allowed | Limit | Verdict | Over allowed | Over limit |
|---|---|---|---|---|---|---|---|
| working set against memory | 0.75 | 25% | 0.75 | 1.00 | ok | 49% | 35% |
| utilisation, counting coordination | 0.95 | 30% | 0.70 | 1.00 | into the margin | 65% | 48% |
| disk fill at horizon | 0.67 | 25% | 0.75 | 1.00 | ok | 44% | 29% |
| utilisation with one host down | 0.66 | 30% | 0.70 | 1.00 | ok | 47% | 30% |
| utilisation at the busy hour | 0.64 | 30% | 0.70 | 1.00 | ok | 46% | 30% |
| fraction of the fleet doing nothing useful | 0.32 | 50% | 0.50 | 1.00 | ok | 1% | 0% |
Source — web_service-reference · the model to explore; each input with a range has a slider
The finished model draws more inputs from the same seed, so the table may differ from ch12’s in a single cell.
A ceiling is a node in the graph, so it is sampled like every other node: one value for each time the model was worked out. Allowed is the Limit less its Headroom: the limit times one minus the headroom. Over allowed is the fraction of the samples whose value is above Allowed. Over limit is the fraction above Limit. Both lines are fixed at the plan’s values; only the ceiling’s own value varies from sample to sample.
The last two columns ask the same fleet a different question from the Verdict: across everything this model thinks could happen, how often is this line crossed?
That changes what the sizing answer is. Not “you need this many hosts”, but “at this many hosts, this is how often the thing you were trying to avoid happens anyway”. The person who signs for the fleet can take responsibility for the second. The first says nothing about risk.
ch12 also showed a bigger fleet against the same ceilings, and ch21 prices it and puts the choice to the person whose decision it is.
The seed
Every sampled result in this book records the seed its random numbers came from, and the sample count, and a hash of the sampler’s source. Run it again with those three and you get the same numbers to the last digit.
That is not fastidiousness. An unseeded simulation gives a result nobody can repeat, and a figure nobody can repeat is a figure nobody can check. This book refuses that everywhere else, and has no reason to start allowing it here.
What this cannot tell you
Whether the model has the right shape. Everything above takes the model’s structure as given and asks what the inputs are worth.
If a cost line is missing, if a ceiling was never declared, or if two quantities were multiplied that should have been added, sampling carries the mistake through every sample and reports a confident interval around the wrong answer. That is structural error.
No technique in this chapter can see it, and it is the subject of ch20 · The missing node.
Whether the shapes are right. A triangular with generous bounds and a lognormal with tight ones will give different intervals for the same input, and nothing here can tell you which was right. The distribution is an assumption like any other, and this book makes you write it in a file with your name on it for that reason.
How the inputs were drawn together. The sampler above draws each input on its own. The intervals on this page were not produced that way. The model declares two pairs of inputs that move together: a host’s price and the network’s price per host, quoted by the same supply chain; and the busy-hour request rate and the processor time each request takes, because a busier service is a slower one per request. The evaluator applies the pairing after the draw, so every figure on this page already carries it, and the chapter has not said so until now. Drawing those pairs independently would make every interval downstream of them narrower, which is the direction that gets a plan approved. ch14 names the pairs and measures what they were worth.
Whether enough samples were drawn. This chapter assumed the number of samples was enough and did not show it. ch14 has the argument, and the way to work it out for a model of your own.
How likely any of this is. The interval is a statement about the model’s declared inputs. It is not a forecast, it carries no track record, and its 95th percentile is not a promise. It is the best available summary of what you have written down. That is worth a great deal more than a single number, and a great deal less than knowledge.
Key takeaways
Give the model a bag of plausible values instead of one, and the bag of answers is the answer. Filling a bag takes two lines: pick a fraction between zero and one at random, and ask the shape’s percentile function for the value there. Each input gets its own draws.
The shape is a claim about the world, and the first thing a reviewer should argue with. Lognormal for what compounds, triangular for an expert’s guess, uniform when the bounds are all you know, and normal for measurement error alone.
Sampling the model is the same walk of the same graph, on arrays instead of numbers. Every node gets its own bag of values, not only the outputs, so you can walk the chain to where the interval got wide.
Read the middle, not the ends. The smallest and largest answers depend on how many you drew; the interval between two percentiles belongs to the model. The point estimate, every input at its middle, is not the middle answer once the model adds lopsided cost lines or takes the largest of several chains.
The ceilings are what the machinery is for. Their last two columns show the fraction of samples over each line. The answer they give is not you need this many hosts but at this many, this is how often the thing you were avoiding happens anyway, which the person who signs for the fleet can be held to.
Problems
Four. The first three are in tests/monte_carlo/ and are graded against definitions the tests
compute for themselves. The fourth has no test and no known answer.
13.1 — Add a distribution. Implement the percentile function for a shape this book does not have: a quantity known only to within a factor, whose density is proportional to one over the value. Derive it the way the chapter derived the triangular’s: the area under the density from the minimum up to a value, set equal to the fraction you are given, then solved for the value. It needs one integral, of one over the value, whose result is a natural logarithm. The rest of the chapter needs only arithmetic, so that step stands out. The test grades your function against the density itself, integrating it at test time, so there is nothing to look up.
def log_uniform_ppf(u: np.ndarray, minimum: float, maximum: float) -> np.ndarray:
"""Problem 13.1 — the percentile function of a shape this book does not have.
A quantity you know to within a factor and no better: as likely to sit anywhere in its range on
a multiplicative scale, so that doubling is as plausible as halving wherever you start. Its
density is proportional to one over the value, between ``minimum`` and ``maximum`` and zero
outside them::
density(x) = 1 / (x * ln(maximum / minimum)) for minimum <= x <= maximum
That is the whole specification. It is the shape for a ballpark: how many distinct label values
a service will turn out to carry, the size of a table nobody has counted.
Your job is the percentile function: given fractions between 0 and 1, return the value each
fraction of the bag is below. Derive it the way the chapter derived the triangular's: the area
under the density from the minimum up to a value, set equal to the fraction, then inverted. It
needs one integral, and it comes out as one line.
The test integrates the density numerically up to each value you return and checks that the area
is the fraction you were given. So there is nothing to look up, and a function that is monotonic
and bounded but the wrong shape fails.
"""
raise NotImplementedError("problem 13.1")The same check at a desk: python3 -m pytest tests/monte_carlo/test_problem_1_ppf.py -m problem
13.2 — Sample a model by hand. The test hands you two of the web service model’s inputs, the engineers the fleet occupies and their fully loaded salary, each with the distribution the model file declares for it. Both are quoted below, with the formula for the annual staff cost they feed. Sample each yourself, without the toolkit’s sampler: each input with its own random fractions. Work the annual staff cost from your samples, one sample at a time, with the model’s formula. Reproduce the 5th and 95th percentiles the book publishes for that cost. Your figures will not match to the last digit: a finite number of samples makes every percentile wobble a little from one set of draws to the next. That wobble is called sampling error, and the test allows for it.
The page’s lognormal_ppf uses two names from outside it: normal_ppf, which you import from
sizing.normal, and Z90, which is normal_ppf(0.9). The point is to find out how small the
machinery is.
staff_fte:
kind: input
decided: outside
unit: dimensionless
label: engineers, full-time equivalent
distribution: {triangular: {minimum: 0.5, likely: 1.0, maximum: 2.0}}
provenance:
kind: assumption
source: >-
Engineers this fleet occupies, full-time equivalent. Triangular, and the shape cannot
express what happens: people are not divisible, so the real spread moves in whole people.
fully_loaded_salary:
kind: input
decided: outside
unit: USD/year
distribution: {lognormal: {p10: 115000, p90: 195000}}
provenance:
kind: assumption
source: "salary, employer costs, tooling and overhead. Lognormal because pay is
right-skewed and cannot go negative; the p90 is a senior engineer in an expensive city"
annual_staff_cost:
kind: derived
unit: USD/year
formula: staff_fte * fully_loaded_salary
def sample_two_inputs(declared: dict[str, dict], seed: int, samples: int) -> dict[str, np.ndarray]:
"""Problem 13.2 — sample a model by hand.
``declared`` holds two of the web service model's inputs, ``staff_fte`` and
``fully_loaded_salary``, each keyed to the distribution the model declares for it, as the file
writes it. One is a triangular::
{"triangular": {"minimum": ..., "likely": ..., "maximum": ...}}
and one is a lognormal::
{"lognormal": {"p10": ..., "p90": ...}}
The test reads both out of ``models/web_service/model.yaml`` and hands them to you, so a change
to the model changes what you are given instead of going stale in a number typed here. Sample
what you are handed.
Return a dictionary with three keys. ``staff_fte`` and ``fully_loaded_salary`` each hold
``samples`` draws from their distribution, seeded with ``seed``; ``annual_staff_cost`` holds
what those draws imply, worked draw by draw through the model's own formula for it:
``staff_fte * fully_loaded_salary``, quoted under the problem on the chapter page.
Do it the way the chapter did: for each input, draw its own random fractions between 0 and 1,
then ask its distribution for the value at each. Drawing both inputs from the same fractions
makes them rise and fall together, which the model does not declare, and the test checks for it.
Use ``numpy`` and ``sizing.normal`` for ``normal_ppf``: the normal's percentile function, which
the lognormal needs. ``Z90`` in the chapter's ``lognormal_ppf`` is ``normal_ppf(0.9)``. Do
**not** use ``sizing.mc`` or ``sizing.evaluate``: the point of this one is to find out how
little machinery there is between a declared distribution and a bag of numbers, and between the
bag and an interval the book publishes.
The test compares your inputs' percentiles with what the declared distributions say, checks that
each input had its own draw, and compares your cost's 5th and 95th percentiles with the ones the
book publishes for the reference scenario. Each comparison allows for the wobble a finite number
of draws brings. These two inputs are declared independent of everything else in the model,
which is what makes the interval reachable by hand; ch14 is about the ones that are not.
"""
raise NotImplementedError("problem 13.2")The same check at a desk: python3 -m pytest tests/monte_carlo/test_problem_2_by_hand.py -m problem
13.3 — Where the point estimate sits. For each of four outputs of the web service model (the host count the model recommends, the five-year total cost, capex, and annual opex), find the fraction of its sampled answers that fall strictly below its point estimate. Some of these fractions sit near one half and some do not. For each one that does not, name the step in its chain that moved the point, and which way. The section Reading the answer gives you the two kinds of step to look for.
def where_the_point_sits(
samples: dict[str, np.ndarray], point: dict[str, float]
) -> dict[str, float]:
"""Problem 13.3 — where the point estimate sits among the sampled answers.
``samples`` holds every output's draws and ``point`` the same outputs' point estimates: the
value the model computes from every input's middle. Return, for every output in ``point``, the
fraction of that output's draws that fall strictly below its point estimate. A draw equal to the
point is not below it. The host count is a whole number, so many of its draws equal the point
exactly.
For a quantity that is one input passed straight through, the fraction is a half. For a product
of two of the model's shapes, it is close to a half. Of the four outputs you are given, some sit
near a half and some do not, by more than the wobble that a finite number of draws brings.
Then finish the last line of this docstring: for each output whose point sits away from the
middle, one sentence naming the step in its chain that moved it, and in which direction. The
test grades the fractions, not the sentences; whoever reads your model will grade the sentences.
What moved it:
"""
raise NotImplementedError("problem 13.3")The same check at a desk: python3 -m pytest tests/monte_carlo/test_problem_3_where_the_point_sits.py -m problem
13.4 — Defend a distribution. No test: the invoices are yours, and so is the shape you would defend.
Take a price you pay, find two years of invoices for it, and decide which of the four shapes in this chapter you would use and why. Then check what the last two years would have looked like under your choice. If the answer embarrasses you, that is the exercise working.
A good answer names the shape, the reason for it and not another, and the band, written the way the model file would declare it. For a lognormal, give the two values you would be surprised to see it under and over (its p10 and p90). For a triangular or a uniform, give its bounds. Write it as a sentence a colleague could disagree with.
The invoices show it wrong, and what counts as wrong depends on the shape you chose.
A lognormal declared by its p10 and p90 expects about one invoice in ten below the lower value and one in ten above the upper, so about one in five outside the band by design. Many more than that outside means the band was too narrow. None outside, and none near either end, means it was too wide to be a claim. A triangular or a uniform claims that nothing falls outside its bounds. Any invoice outside them means the bounds were wrong. The chapter argues that a normal is the wrong default for a price. An answer that chooses one has to answer that argument first.
Where to go next
Metropolis and Ulam’s original paper [Metropolis & Ulam (1949)] is seven pages, is readable without any statistics, and is a useful corrective to the idea that this is a modern technique.
numpy.random’s documentation on generators and seeding is worth twenty minutes, particularly
the part about why default_rng exists and what it replaced.
ch14 picks up the two things this chapter used without establishing: the correlations the intervals above already carry, and the sample count.
Appendix B quotes the complete sizing/mc.py and
sizing/normal.py, showing the order a model run calls them.