# inventory.safety-stock
Safety stock is the buffer held on top of expected lead-time demand, so that
ordinary ups and downs in demand or supply do not cause a stock-out. Two
methods, chosen by `method`:
**`service-level`** - the statistical method:
safety stock = z x sqrt(L x sd^2 + d^2 x sL^2)
where `z` is the standard normal quantile for the service level, `L` the
average lead time, `sd` the standard deviation of demand per period, `d` the
average demand per period and `sL` the standard deviation of the lead time.
When lead time is fixed (`leadTimeStdDev` null or 0) this is the familiar
`z x sd x sqrt(L)`, and `averageDemand` is not needed. Demand and lead time must
be in the same period: a daily standard deviation with a lead time in days.
`stats.standard-deviation` gives `sd` from a demand history.
The service level is the **cycle service level**: the chance of not running out
during one replenishment cycle. It is not the fill rate. `z` comes from a table
(`data/z-scores.json`) of the levels people actually use, 50% to 99.9%, rather
than an inverse normal function, which would be approximated differently in each
language. Each value is the quantile rounded to four decimal places, e.g. 95% is
1.6449 and 97.5% is 1.9600. A level not in the table is an error; round to one
that is.
**`max-minus-average`** - the rule of thumb that needs no statistics:
safety stock = maxDemand x maxLeadTime - averageDemand x leadTime
It is an error for the worst case to be below the average case.
**Rounding.** Both methods compute in floating point, which is fine for a
statistical estimate but can land a whisker above a whole number
(`2.2 x 25` is `55.00000000000001`). The figure is rounded to 6 decimal places
(half away from zero) and then **up** to whole units, so 50.000000000000014
is 50 and not 51, and 98.694 is 99. All values must be finite and not negative.
Sources: z values are the standard normal quantiles, checked against NIST/SEMATECH
e-Handbook of Statistical Methods, section 1.3.6.7.1, "Cumulative Distribution
Function of the Standard Normal Distribution"
(https://www.itl.nist.gov/div898/handbook/eda/section3/eda3671.htm), and
computed to four places with Python's `statistics.NormalDist().inv_cdf`. The
combined-variability formula is the standard one in Silver, Pyke and Thomas,
*Inventory and Production Management in Supply Chains*, 4th ed., ch. 6.