Techniquecore
Monte Carlo tolerance analysis
Also called statistical tolerance simulation.
Samples each part dimension from its distribution, solves the assembly for each sample and reads off the distribution of the assembly gap, nonlinear effects included.
Monte Carlo tolerance analysis estimates the variation of an assembly output by simulation. It draws a random value for every toleranced dimension from an assumed distribution, solves the assembly exactly for that sample, and repeats this times. The sample of outputs gives the mean, the spread and the fraction of assemblies outside the specification limits, the reject rate. It is Monte Carlo integration applied to the assembly function. Unlike the direct linearization method it uses no first-order expansion, so it sees the curvature of the assembly function, a skewed output and samples whose parts do not fit together. Its cost is assembly solves, and its result has a sampling error of order , which this page states and bounds.
In plain words
Build many virtual assemblies. For each one, pick every part size at random, the way a real machine would make it, and put the parts together on the computer. Write down the gap or angle that you get, and whether the assembly is good. After many assemblies, the list tells you the average result, how much it spreads, and what fraction is bad. You do not need a formula for the output, only a way to compute it for one set of parts. The method also shows effects that a straight-line estimate misses, such as an average that moves away from the nominal value, or parts that sometimes do not fit at all. The price is many solves, and an answer that is itself random. So you must also say how far the answer can be from the truth.
When it applies
The technique needs two things. The first is an assembly function that computes the output for one set of dimensions, or reports that the parts do not assemble. It can be a closed formula, a solve of vector loops, a chain of torsors or a full contact simulation. The second is a probability model of the dimensions.
The model of variation. Each toleranced dimension is a random variable with a known distribution, and the dimensions are independent unless a joint distribution is given. The code of this page uses two common choices for a tolerance : a normal distribution with mean at the nominal value and standard deviation , and a uniform distribution on . The output is , evaluated exactly. There is no linearization and no small-angle approximation in the technique itself. If is a first-order model, such as a small displacement torsor or Jacobian-torsor chain, the simulation inherits that first-order approximation, and then only the propagation through is exact.
Use it when the assembly function is far from linear over the tolerance range, when a sample can fail to assemble, when the input distributions are far from normal, when the reject rate itself is wanted, or to check a linear method. A linear method such as tolerance stack-up or DLM is cheaper and exact on linear stacks, so simulation adds nothing there except a check.
The template
Let give the distribution of each dimension, let return the output or NO-FIT, and let be the specification limits of the output.
MC-TOLERANCE(f, D, N, seed, lo, hi)- 1
rejects ← 0; start an empty running mean and variance Y; rng ← generator from seed - 2
for i ← 1 to N do - 3
x ← one independent draw of every dimension from D, using rng - 4
y ← f(x) ▷ solve the assembly exactly - 5
if y = NO-FIT then rejects ← rejects + 1; continue - 6
if y < lo or y > hi then rejects ← rejects + 1 - 7
add y to Y ▷ Welford's update - 8
p ← rejects / N; se ← sqrt(p (1 − p) / N) - 9
return mean(Y), var(Y), p, se, a confidence interval for p
The holes are , the distributions and the generator. Line L3 draws the dimensions in a fixed order from one seeded generator (the code uses Python's random.Random, a Mersenne twister), so a run can be repeated exactly. Line L7 keeps the running mean and the sum of squared deviations by Welford's update, which avoids the cancellation of the formula . A sample that does not assemble counts as a reject and does not enter the mean and variance, so these describe the assemblies that are built.
The reject-rate estimate is unbiased. Let be the probability that one sample is a reject, a sample that does not fit or has its output outside . Let be the indicator of the event that sample is a reject. Then , and line L8 computes . By linearity of expectation, .
Its standard error is . Each is a Bernoulli variable with variance , because . The samples are independent, so the variances add: , and . The standard error is its square root. The sum has the binomial distribution with parameters and . Line L8 replaces the unknown by in the formula.
The relative error is . So a reject rate of known to within 10 percent at one standard error needs samples. The error falls as for any number of dimensions, the property of Monte Carlo integration, and the law of large numbers gives with probability .
Confidence intervals. By the central limit theorem, is close to standard normal for large . Let be the 0.975 quantile of the standard normal. The Wald interval puts in the standard error. The Wilson score interval instead keeps in it and solves for . This is the quadratic , whose roots are
Both intervals have coverage close to 95 percent only in the limit. For small the Wald interval covers badly, and with no rejects it is the single point . The Wilson interval keeps close to its nominal coverage (Agresti and Coull 1998). The exact Clopper-Pearson interval has coverage at least 95 percent for every .
No rejects in samples. If no sample is a reject, the exact one-sided 95 percent upper bound on is . Proof. The probability of no reject is , which decreases in . A value gives , so the test that rejects when no reject is seen has level , and the set of values of that it does not reject is . Since , . This is the rule of three (Hanley and Lippman-Hand 1983).
The output moments. The sample mean of the assembled outputs is an unbiased estimate of , with standard error for assembled samples. The sample variance with divisor is an unbiased estimate of . For a normal output its standard error is , which is about percent of for .
Cost. Each sample costs one draw per dimension and one evaluation of , so the run costs time for dimensions and an assembly solve of cost . For vector loops is a few Newton steps. The extra space is , since the running moments replace the list of outputs; keep the list only for a histogram or quantiles.
Results. The proofs above are mathematical results. The numbers in the next section are measured with the code of this page and the stated seeds. There are no standard benchmarks for tolerance analysis, so no other numbers are given.
Classic examples
A linear stack against DLM. The housing gap of the stack-up page, with and , is linear, so DLM is exact for it. With normal dimensions () the predicted variance is . A run with and seed 2026 gives the mean and the variance , within one standard error of the variance (). With uniform dimensions the predicted variance is , and the same run gives . With the lower limit and normal dimensions, the exact reject rate is . The run gives rejects, , a standard error of and the Wilson interval , which contains the exact value. The tests check these agreements within four standard errors.
The one-way clutch. The pressure angle of Chase's clutch is , with nominal , , mm and (see the DLM page). If , the roller does not fit. With normal dimensions, the same tolerance on each, and seed 31:
| (mm) | DLM standard deviation | MC standard deviation | MC mean minus | second-order shift | samples that do not fit |
|---|---|---|---|---|---|
At the smallest tolerance the linear result is good. As grows, the simulated spread exceeds the linear one and the mean moves below the nominal angle by about the second-order term of the DLM correctness proof, which DLM does not report. At some samples do not assemble. With uniform dimensions on , of the samples do not fit, with the Wilson interval ; DLM gives a finite angle for every one of them.
Zero rejects. At every sample assembles. If a failure to fit is the only reject, the run has no reject and . The Wald interval is then , which claims too much. The Wilson upper limit for is , and the exact one-sided bound is , about .
Variations
- Variance reduction. Latin hypercube sampling (McKay, Beckman and Conover 1979) stratifies each input. When is monotone in each input, the variance of its mean is no larger than that of plain sampling, and it is much smaller when is close to a sum of functions of single inputs, as many assemblies are. Stratified sampling and quasi-Monte Carlo points do the same with other designs. The interval of this page assumes independent samples, so these designs need their own error estimate, such as independent replicates.
- Rare rejects. For a reject rate in parts per million, plain sampling needs of the order of . Importance sampling draws more samples near the limits and weights them back.
- Other distributions. Any distribution with a sampler fits line L3: a truncated normal for a process with inspection, a shifted mean for tool wear, or an empirical distribution from measured parts. Correlated dimensions need a joint sampler.
- Geometric tolerances. For form, orientation and position tolerances, line L3 draws a small displacement of each feature inside its tolerance zone, a point of a tolerance map or a torsor box, and is the torsor chain. The approximation is then the first-order one of the torsor model.
- Sensitivities from the sample. A regression of the outputs on the inputs estimates the sensitivities, which the DLM gives exactly at the nominal point.
- Allocation. Simulation can check the result of tolerance allocation, which uses a linear stack model.
Pitfalls
- Too few samples for a small reject rate. With samples, rates far below are invisible. Report the interval, not only .
- The Wald interval at zero or few rejects. It gives a zero width interval at zero rejects and poor coverage near it. Use the Wilson or Clopper-Pearson interval, or the bound .
- The distribution is an assumption. The rule is a convention, and real processes have shifted means and other shapes. The result is only as good as the model of variation; it is not a property of the drawing.
- Silent no-fit samples. If returns a value for parts that do not assemble, for example a clipped , the simulation hides the failures. Make detect them, and count them as rejects.
- Correlated dimensions. Two dimensions made in one setup are not independent. Independent sampling then gives the wrong spread.
- Seeds and generators. Without a fixed seed a run cannot be repeated, and two methods compared with different random numbers differ by sampling noise as well. Use the same seed, or common random numbers, for comparisons.
- Inherited linearization. A simulation through a first-order torsor or Jacobian model is only as accurate as that model; it does not remove the small-angle approximation.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/monte-carlo-tolerance-analysis/. The authors are listed in prov/XCJC4F.jsonl.
"""Monte Carlo tolerance analysis.
Each part dimension is a random variable given by a spec (kind, nominal, T):
- ("normal", m, T): normal with mean m and standard deviation T / 3;
- ("uniform", m, T): uniform on [m - T, m + T].
The assembly function f maps a dict of dimensions to the output, or to None
when the parts do not assemble. The simulation draws N independent samples
with random.Random(seed), evaluates f exactly on each, and returns the sample
mean and variance of the output and the estimated reject rate, with its
standard error and two confidence intervals.
"""
import math
import random
Z95 = 1.959963984540054 # the 0.975 quantile of the standard normal
def draw(rng, spec):
kind, m, T = spec
if kind == "normal":
return rng.gauss(m, T / 3.0)
if kind == "uniform":
return rng.uniform(m - T, m + T)
raise ValueError("unknown distribution %r" % (kind,))
def wald_interval(rejects, n, z=Z95):
p = rejects / n
h = z * math.sqrt(p * (1 - p) / n)
return max(0.0, p - h), min(1.0, p + h)
def wilson_interval(rejects, n, z=Z95):
p = rejects / n
d = 1 + z * z / n
centre = (p + z * z / (2 * n)) / d
h = z / d * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
return max(0.0, centre - h), min(1.0, centre + h)
def zero_reject_upper_bound(n, alpha=0.05):
"""Exact one-sided upper bound on p when no reject is seen in n samples."""
return 1 - alpha ** (1.0 / n)
def simulate(f, specs, n, seed, lower=-math.inf, upper=math.inf):
"""Run n samples. specs is a dict name -> (kind, nominal, T).
An output outside [lower, upper], or a sample that does not assemble,
is a reject. Mean and variance are over the samples that assemble.
"""
rng = random.Random(seed)
names = sorted(specs)
rejects = 0 # @line L1
no_fit = 0
count, mean, m2 = 0, 0.0, 0.0
for _ in range(n): # @line L2
x = {name: draw(rng, specs[name]) for name in names} # @line L3
y = f(x) # @line L4
if y is None: # @line L5
no_fit += 1
rejects += 1
continue
if y < lower or y > upper: # @line L6
rejects += 1
count += 1 # @line L7
d = y - mean
mean += d / count
m2 += d * (y - mean)
p = rejects / n # @line L8
se = math.sqrt(p * (1 - p) / n)
var = m2 / (count - 1) if count > 1 else float("nan")
return { # @line L9
"n": n,
"assembled": count,
"no_fit": no_fit,
"mean": mean,
"var": var,
"rejects": rejects,
"p": p,
"se": se,
"wald": wald_interval(rejects, n),
"wilson": wilson_interval(rejects, n),
"upper_if_zero": zero_reject_upper_bound(n) if rejects == 0 else None,
}
test_monte_carlo_tolerance_analysis.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/monte-carlo-tolerance-analysis/. The authors are listed in prov/XCJC4F.jsonl.
import math
import random
import pytest
from monte_carlo_tolerance_analysis import simulate, wilson_interval, zero_reject_upper_bound
STACK = {"A": 50.0, "B": 20.0, "C": 15.0, "D": 14.8}
STACK_T = {"A": 0.10, "B": 0.05, "C": 0.05, "D": 0.05}
COEF = {"A": 1.0, "B": -1.0, "C": -1.0, "D": -1.0}
def gap(x):
return x["A"] - x["B"] - x["C"] - x["D"]
def phi(z):
return 0.5 * (1 + math.erf(z / math.sqrt(2)))
def dlm_linear(sd):
"""DLM on the linear stack: mean = nominal output, variance = sum a_j^2 sd_j^2."""
mean = sum(COEF[n] * STACK[n] for n in STACK)
var = sum((COEF[n] * sd[n]) ** 2 for n in STACK)
return mean, var
@pytest.mark.parametrize("kind,div", [("normal", 3.0), ("uniform", math.sqrt(3.0))])
def test_linear_stack_agrees_with_dlm(kind, div):
n = 200_000
specs = {k: (kind, STACK[k], STACK_T[k]) for k in STACK}
res = simulate(gap, specs, n, seed=2026)
mean, var = dlm_linear({k: STACK_T[k] / div for k in STACK})
se_mean = math.sqrt(var / n)
# For a normal output the sample variance has standard error var * sqrt(2 / (n - 1)).
# A sum of uniforms has lighter tails, so this bound is conservative for it.
se_var = var * math.sqrt(2.0 / (n - 1))
assert abs(res["mean"] - mean) <= 4 * se_mean
assert abs(res["var"] - var) <= 4 * se_var
assert res["assembled"] == n
def test_reject_rate_matches_exact_normal_probability():
n = 200_000
specs = {k: ("normal", STACK[k], STACK_T[k]) for k in STACK}
res = simulate(gap, specs, n, seed=7, lower=0.1)
mean, var = dlm_linear({k: STACK_T[k] / 3 for k in STACK})
p = phi((0.1 - mean) / math.sqrt(var))
assert 0.011 < p < 0.012
assert abs(res["p"] - p) <= 4 * math.sqrt(p * (1 - p) / n)
lo, hi = res["wilson"]
assert lo < p < hi
def test_estimator_is_unbiased_with_the_stated_standard_error():
"""Many short runs: the average of p_hat is p and its spread is sqrt(p(1-p)/N)."""
p_true, n, runs = 0.1, 500, 400
specs = {"x": ("uniform", 0.5, 0.5)} # uniform on [0, 1]
ests, covered = [], 0
for r in range(runs):
res = simulate(lambda x: x["x"], specs, n, seed=1000 + r, upper=1 - p_true)
ests.append(res["p"])
lo, hi = res["wilson"]
covered += lo <= p_true <= hi
avg = sum(ests) / runs
var = sum((e - avg) ** 2 for e in ests) / (runs - 1)
se_true = math.sqrt(p_true * (1 - p_true) / n)
assert abs(avg - p_true) <= 4 * se_true / math.sqrt(runs)
assert abs(var / se_true ** 2 - 1) <= 0.3
assert covered / runs >= 0.90
def test_zero_rejects_upper_bound():
n = 3000
res = simulate(lambda x: x["x"], {"x": ("uniform", 0.0, 1.0)}, n, seed=1, lower=-2, upper=2)
assert res["rejects"] == 0 and res["p"] == 0 and res["se"] == 0
u = res["upper_if_zero"]
assert u == pytest.approx(zero_reject_upper_bound(n))
assert (1 - u) ** n == pytest.approx(0.05)
assert 0.9 * 3 / n < u < 3 / n
def test_parts_that_do_not_fit_are_rejects():
n = 20_000
specs = {"x": ("normal", 0.0, 3.0)}
res = simulate(lambda x: None if x["x"] > 1 else x["x"], specs, n, seed=5)
rng = random.Random(5)
expected = sum(rng.gauss(0.0, 1.0) > 1 for _ in range(n))
assert res["no_fit"] == expected == res["rejects"]
assert res["assembled"] == n - expected
assert abs(res["p"] - (1 - phi(1.0))) <= 4 * math.sqrt(0.16 * 0.84 / n)
def test_same_seed_same_result():
specs = {k: ("normal", STACK[k], STACK_T[k]) for k in STACK}
a = simulate(gap, specs, 5000, seed=99, lower=0.1)
b = simulate(gap, specs, 5000, seed=99, lower=0.1)
assert a == b
CLUTCH = {"a": 27.645, "c": 11.43, "e": 50.8}
def clutch_phi(x):
q = (x["a"] + x["c"]) / (x["e"] - x["c"])
return math.acos(q) if q <= 1 else None
def test_nonlinear_mean_shift_matches_second_order_estimate():
"""On the clutch the output mean moves by about 1/2 sum H_jj sigma_j^2, which DLM does not see."""
T = 0.05
sd = T / 3
n = 100_000
specs = {k: ("normal", CLUTCH[k], T) for k in CLUTCH}
res = simulate(clutch_phi, specs, n, seed=31)
phi0 = clutch_phi(CLUTCH)
h = 1e-3
bias = 0.0
for k in CLUTCH:
xp, xm = dict(CLUTCH), dict(CLUTCH)
xp[k] += h
xm[k] -= h
hkk = (clutch_phi(xp) - 2 * phi0 + clutch_phi(xm)) / (h * h)
bias += 0.5 * hkk * sd * sd
se = math.sqrt(res["var"] / n)
assert abs(bias) > 8 * se
assert abs((res["mean"] - phi0) - bias) <= 4 * se + 0.15 * abs(bias)
def test_wilson_interval_endpoints():
lo, hi = wilson_interval(0, 100)
assert lo == pytest.approx(0, abs=1e-15) and 0.03 < hi < 0.04
lo, hi = wilson_interval(50, 100)
assert lo == pytest.approx(1 - hi)
Exercises
- Show that the Wilson interval with is symmetric about , and that with its lower limit is and its upper limit is .
- How many samples are needed to show, with 95 percent confidence and no rejects seen, that the reject rate is below 100 parts per million?
- For the clutch at , compute from the closed form of and compare it with the table.
- A sample is a reject when it breaks the lower or the upper limit. Show that the indicators of the two events are not independent, and that the estimate of the total reject rate is still unbiased.
- Show that for a linear and normal inputs, the simulated output is exactly normal with the RSS variance, so that the only error of the simulation is the sampling error.
References
- Christian P. Robert and George Casella, Monte Carlo Statistical Methods, second edition, Springer, 2004, Chapter 3, Monte Carlo integration (the empirical average, its variance and its convergence)
- Edwin B. Wilson, Probable inference, the law of succession, and statistical inference, Journal of the American Statistical Association 22(158), 1927, pp. 209 to 212 (the score interval for a proportion)
- C. J. Clopper and E. S. Pearson, The use of confidence or fiducial limits illustrated in the case of the binomial, Biometrika 26(4), 1934, pp. 404 to 413 (exact confidence limits for a binomial proportion)
- Alan Agresti and Brent A. Coull, Approximate is better than "exact" for interval estimation of binomial proportions, The American Statistician 52(2), 1998, pp. 119 to 126 (the poor coverage of the Wald interval and the score interval)
- James A. Hanley and Abby Lippman-Hand, If nothing goes wrong, is everything all right? Interpreting zero numerators, JAMA 249(13), 1983, the rule of three for zero events
- Michael D. McKay, Richard J. Beckman and William J. Conover, A comparison of three methods for selecting values of input variables in the analysis of output from a computer code, Technometrics 21(2), 239 to 245, 1979, the whole paper (Latin hypercube sampling against simple random sampling)
- Paul J. Drake, Jr. (editor), Dimensioning and Tolerancing Handbook, McGraw-Hill, 1999, the chapters on statistical tolerance analysis of assemblies (general locator)
- Hua Chen, Sun Jin, Zhimin Li and Xinmin Lai, A comprehensive study of three dimensional tolerance analysis methods, Computer-Aided Design 53, 1 to 13, 2014, the comparison of the 3D tolerance analysis methods (general locator)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag XCJC4F Edit this page History Report an error Markdown