Monte Carlo Tolerance Stack-Up Python Script Generator
Spreadsheets handle worst case and RSS well, but a simulation is better when the stack has many terms or when you want an out-of-limit rate in parts per million. This generator writes a short, dependency-free Python script you can run and modify.
Fill in
3 means the tolerance equals 3 sigma (Cp of 1.0). Use 4 for Cp of 1.33.
Python script
import math
import random
import statistics
random.seed(42)
N = 200000
SIGMA_DIV = 3
GAP_MIN = 0.10
GAP_MAX = 0.80
# (name, nominal, +/- tolerance, direction) ; direction +1 adds to the gap, -1 subtracts
DIMS = [
('housing_depth', 42.00, 0.10, 1),
('bearing_width', 12.00, 0.05, -1),
('shaft_shoulder', 28.00, 0.08, -1),
('spacer', 1.50, 0.02, -1),
]
nominal_gap = sum(d * nom for _, nom, _, d in DIMS)
worst_range = sum(tol for _, _, tol, _ in DIMS)
rss_range = math.sqrt(sum(tol ** 2 for _, _, tol, _ in DIMS))
gaps = []
for _ in range(N):
gap = 0.0
for _, nom, tol, d in DIMS:
gap += d * random.gauss(nom, tol / SIGMA_DIV)
gaps.append(gap)
out_low = sum(1 for g in gaps if g < GAP_MIN)
out_high = sum(1 for g in gaps if g > GAP_MAX)
ppm = (out_low + out_high) / N * 1e6
print('Nominal gap : %.4f mm' % nominal_gap)
print('Worst case range : %.4f to %.4f mm' % (nominal_gap - worst_range, nominal_gap + worst_range))
print('RSS range (+/-) : %.4f to %.4f mm' % (nominal_gap - rss_range, nominal_gap + rss_range))
print('Simulated mean : %.4f mm' % statistics.mean(gaps))
print('Simulated std dev : %.4f mm' % statistics.pstdev(gaps))
print('Simulated min/max : %.4f / %.4f mm' % (min(gaps), max(gaps)))
print('Below %.2f mm : %d of %d' % (GAP_MIN, out_low, N))
print('Above %.2f mm : %d of %d' % (GAP_MAX, out_high, N))
print('Out of limits : %.0f PPM' % ppm)
print('Worst case fits? :', nominal_gap - worst_range >= GAP_MIN and nominal_gap + worst_range <= GAP_MAX)Each dimension is modeled as a normal distribution centered on nominal with a standard deviation of tolerance divided by the sigma value. This ignores mean shift, non-normal distributions and geometric variation (position, form, tilt), so treat the output as a design aid and validate with measured data. Needs Python 3 and no extra packages.
Feed real measurements into tolerance analysis
Optional: a short review of how measured dimensions from your ERP or quality database could drive this analysis.
Optional. The tool and every export work without this. No spam.
How to use the generator
Enter each dimension in the stack with its nominal and plus-minus tolerance. Set the direction to 1 if the dimension increases the gap, and -1 if it decreases it. Then enter the minimum and maximum acceptable gap. The sigma setting decides how wide the simulated distribution is compared with the tolerance. Copy the script, save it as a .py file and run it with Python 3. It prints the worst case range, the RSS range, the simulated statistics and the estimated number of assemblies outside the gap limits.
- Add more dimensions by copying one tuple in the DIMS list
- Raise samples to 1,000,000 for a finer tail estimate
- Change the random seed to check that the answer is stable
Worst case, RSS and Monte Carlo
Worst case adds every tolerance, so it guarantees fit for every assembly if all parts are within limits. RSS takes the square root of the sum of squares, which assumes independent, centered, normal variation and gives a narrower range. Monte Carlo draws random values for each dimension and builds thousands of virtual assemblies. It matches RSS for simple linear stacks, but it also lets you change the distribution, add a mean shift or use non-linear relationships.
How to read the result
If the worst case range sits inside the gap limits, the design always assembles with in-tolerance parts. If only the RSS range fits, you are accepting a small, predictable rejection rate, and the PPM line tells you how small. With the default inputs, the nominal gap is 0.50 mm, the worst case range is 0.25 to 0.75 mm, and the simulation shows no failures against 0.10 to 0.80 mm. A non-zero PPM means a tolerance review or a process capability check.
Limits of the model
The script assumes a one-dimensional linear stack, and every part is centered on nominal. Real processes drift, so a Cpk below the Cp used here will give a higher failure rate than reported. Geometric tolerances, thermal expansion and assembly shifts are not modeled. Use the output as a design aid, and confirm against measured data once production parts exist.
Frequently Asked Questions
Why divide the tolerance by 3 for sigma?
Dividing by 3 assumes the process is centered and its natural spread, plus or minus 3 sigma, just fills the tolerance, which is a Cp of 1.0. A capable process with Cp of 1.33 would use 4. Use measured standard deviations when you have them.
How many samples are enough?
For a stable mean and standard deviation, 10,000 is usually enough. To see rare failures in the parts per million range you need hundreds of thousands or more. Run with two different seeds and check that the PPM figure is roughly stable.
When should I use worst case instead?
Use worst case for safety-critical fits, small production volumes, or where any single failure is unacceptable. Statistical methods are reasonable for high volume work with demonstrated process capability, and where the customer or standard allows them.
Can I model a non-normal distribution?
Yes. Replace random.gauss with random.uniform for a uniform spread or random.triangular for a skewed one. The structure of the script stays the same, which is the main advantage of simulation over a closed-form RSS formula.
Netray can pull measured dimensions from your ERP or quality system into a script like this, so tolerance analysis uses real process data instead of assumed sigma values.
Related Tools
Assembly Tolerance Stack Worst Case vs RSS Calculator
Add up the contributors in a linear stack and see the minimum gap by worst case, root-sum-square and a 1.5x modified RSS.
Engineering & PLMBonus Tolerance (MMC) Position Calculator
Calculates the bonus tolerance gained as a feature departs from maximum material condition and compares the total allowed position zone to the measured error.
Quality & InspectionTolerance vs Process Capability Review Worksheet
A worksheet that checks each toleranced feature against measured process mean and standard deviation, returning Cp, Cpk and predicted defects per million.
Developer ToolsDimensional Inspection Out-of-Tolerance SQL Query Generator
Fill in your inspection results table and column names to get SQL that finds out-of-tolerance measurements and summarizes them by characteristic.
More Engineering & PLM tools
See all- BOM Error Cost of Poor Quality Calculator
- ISO 286 IT Tolerance Grades Table
- GD&T Symbols Reference Table
- ISO 2768 General Tolerances Table
- Bolt Circle Hole Coordinates Calculator
- Engineering Drawing Review Checklist
- Linear Thermal Expansion Calculator (Two Materials)
- Press Fit Interference Pressure and Force Calculator
- Engineering Drawing Release Request Template