100 Exercises / numerical computation / Numerical Computation: 100 Exercises
Introduction to Numerical Computation in Manufacturing | Learning Floating Point and Errors with Python: 10 Exercises
Explore floating-point precision, rounding, cancellation, overflow, and error tolerances in Python using manufacturing measurements and costs.
Manufacturers use computer summaries of sensor readings, costs, yields, and equipment utilization for quality and investment decisions. Floating-point values approximate real numbers with limited precision. Using a fictional precision-parts factory, this notebook examines how representation and rounding affect those decisions.
This series, “100 Numerical Computations for Manufacturing Decision-Making,” covers 100 questions that teach step-by-step learning from floating-point numbers to equations, linear algebra, interpolation, calculus, differential equations, and optimization, all linked to real-world decision-making. The first installment covers the foundations No.001 to No.010.
Note This material was adapted from notebooks used in corporate training by Surikobo or its representative, Hiroshi Wayama, with permission from the participating companies.
All examples use fictional data, not records from real companies or factories.
1. Introduction: Practical Challenges in Manufacturing Covered in This Article
A precision-parts factory may handle tolerances of a few micrometers, quantities of millions of components, and second-by-second equipment logs. Even a mathematically correct formula can produce different totals because of data types and operation order, affecting pass/fail, anomaly, or profitability assessments.
2. Common Situations on Site
- Display digits and data types differ between Excel, PLC, database, and Python
- Even
0.1 + 0.2can produce an internal value different from the expected decimal result - Even if you make a tiny adjustment to the huge cumulative value, it won’t be reflected
- When the difference between close measurements is taken, the significant digit is lost.
- Judging accuracy from absolute error without considering the reference scale
3. Why is this issue difficult to judge?
Since the screen displays the results in a rounded form, internal errors are hard to see, whereas in threshold determination, even slight differences can change the conclusion. Also, whether to look at absolute error or relative error depends on the intended use. In quality assurance, it is necessary to design calculation methods and judgment rules, including units, resolution, and tolerances.
4. Overview of the Exercises
| No. | Theme | Key Issues in Manufacturing |
|---|---|---|
| 001 | What is numerical computation? | The Relationship Between Theoretical Values, Approximate Values, and Decision-Making |
| 002 | floating-point representation | Difference between display values and internal values |
| 003 | IEEE 754 | Data types, signs, exponents, mantissa |
| 004 | rounding error | How to round the amounts and aggregation |
| 005 | Cancellation | Differences in Nearby Measurements |
| 006 | Loss of Small Addends | Micro-addition to large cumulative values |
| 007 | overflow | Divergence of indicators and model calculations |
| 008 | Underflow | Loss of Minute Probability |
| 009 | Machine Epsilon | Gap between 1 and the next larger representable value |
| 010 | Evaluation of numerical errors | Absolute error, relative error, and acceptable criteria |
5. Preparing the Python environment
Run the cells in order in Jupyter Notebook. [IN: n] identifies a code cell; [OUT: n] contains its tables, values, and figures. Low-order digits and runtimes may vary with library versions, BLAS, and hardware.
It does not rely on external data and reproduces using NumPy, pandas, and matplotlib. Random seed is fixed so that the same result is achieved.
Show setup code: libraries and display settings
import sys
from IPython.display import display
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import japanize_matplotlib
SEED = 42
rng = np.random.default_rng(SEED)
pd.set_option("display.precision", 10)
print(f"Python : {sys.version.split()[0]}")
print(f"NumPy : {np.__version__}")
print(f"pandas : {pd.__version__}")
print(f"matplotlib : {matplotlib.__version__}")
Python : 3.14.4
NumPy : 2.5.1
pandas : 3.0.3
matplotlib : 3.11.0
6. Creating the Fictional Data
We simulate measurements of 1,000 shafts with a nominal dimension of 50.000 mm and a tolerance of ±0.010 mm. We retain both the generated values and values rounded to the display resolution of 0.001 mm. The unrounded values are references for this simulation, not guaranteed true measurements. We also generate quantities and unit prices for cost aggregation.
Show setup code: generate the fictional data
n = 1_000
measurement_raw = 50.0 + rng.normal(0, 0.004, n)
measurement_display = np.round(measurement_raw, 3)
factory_df = pd.DataFrame(
{
"lot": np.repeat(["L-A", "L-B", "L-C", "L-D"], n // 4),
"measurement_raw_mm": measurement_raw,
"measurement_display_mm": measurement_display,
"quantity": rng.integers(80, 151, n),
"unit_cost_yen": rng.uniform(118.0, 123.0, n),
}
)
factory_df.head()
| lot | measurement_raw_mm | measurement_display_mm | quantity | unit_cost_yen | |
|---|---|---|---|---|---|
| 0 | L-A | 50.0012188683 | 50.001 | 93 | 120.4056155088 |
| 1 | L-A | 49.9958400636 | 49.996 | 125 | 121.9110559763 |
| 2 | L-A | 50.0030018048 | 50.003 | 108 | 121.7399506448 |
| 3 | L-A | 50.0037622589 | 50.004 | 104 | 122.0753654811 |
| 4 | L-A | 49.9921958592 | 49.992 | 129 | 120.2412031659 |
7. No.001: What is Numerical Computation?
Practical Use
Numerical computation uses finite-precision representations to calculate quantities such as equation roots and measurement summaries. An average dimension is the sum of measurements divided by their count. To use it for quality decisions, also specify data types, missing-value handling, rounding, and tolerances.
Model and Method
If the measurement is , then the average is
In numerical computations, input errors, algorithm approximation errors, and finite precision rounding errors are propagated to the results. The goal is not to “perfectly reproduce the true value,” but to ensure the accuracy necessary for decision-making.
Check with Python
summary_001 = factory_df["measurement_raw_mm"].agg(
["count", "mean", "std", "min", "max"]
)
summary_001.to_frame("Measurement value (mm)")
| Measurement value (mm) | |
|---|---|
| count | 1000.0000000000 |
| mean | 49.9998844338 |
| std | 0.0039568684 |
| min | 49.9854063487 |
| max | 50.0127154147 |
Interpreting the Results
By listing not only the mean but also the standard deviation and range, you can distinguish between process location and spread. It is important that numerical results are not just isolated numbers, but managed together with units, calculation conditions, and determination objectives.
8. No.002: Floating-Point Representation
Practical Use
Many decimal fractions have no finite binary representation. Cost totals and threshold comparisons may therefore use slightly different internal values even when their displayed values look identical.
Model and Method
Floating-point numbers are conceptually defined using sign , mantissa , base , and exponent
Python’s usual float is a binary64 double-precision value. For precise decimal calculation of amounts, integers (such as sen) and decimal.Decimal are also options.
Check with Python
from decimal import Decimal
floating = 0.1 + 0.2
exact_decimal = Decimal("0.1") + Decimal("0.2")
pd.DataFrame(
{
"Calculation method": ["binary64 float", "Decimal(Generated from a string)"],
"Results": [format(floating, ".17f"), str(exact_decimal)],
"0.3Matches": [floating == 0.3, exact_decimal == Decimal("0.3")],
}
)
| Calculation method | Results | 0.3Matches | |
|---|---|---|---|
| 0 | binary64 float | 0.30000000000000004 | False |
| 1 | Decimal(Generated from a string) | 0.3 | True |
Interpreting the Results
float results are close to 0.3, but they don’t exactly match. For sensor processing, you select expressions that fit your purpose, such as comparison with tolerance, and for accounting, decimal or integer for the smallest currency unit.
9. No.003:IEEE 754
Practical Use
When float32 and float64 coexist among instruments, databases, and analytical platforms, not only storage capacity but also significant bits and calculation results change. You need to specify the data type in the interface specification.
Model and Method
IEEE 754 binary32 has one sign bit, eight exponent bits, and 23 stored fraction bits; binary64 has one, eleven, and 52. Normalized numbers have an implicit leading 1, giving significand precisions of 24 and 53 bits.
Check with Python
rows = []
for dtype in [np.float32, np.float64]:
info = np.finfo(dtype)
rows.append(
{
"type": dtype.__name__,
"bytes": info.bits // 8,
"10Reference for Base Significant Figures": info.precision,
"maximum value": info.max,
"Minimal normalized positive number": info.tiny,
}
)
pd.DataFrame(rows)
| type | bytes | 10Reference for Base Significant Figures | maximum value | Minimal normalized positive number | |
|---|---|---|---|---|---|
| 0 | float32 | 4 | 6 | 3.4028234664e+38 | 1.1754943508e-38 |
| 1 | float64 | 8 | 15 | 1.7976931349e+308 | 2.2250738585e-308 |
Interpreting the Results
float32 is memory-efficient but generally achieves about 7 digits of accuracy. Long-term cumulative values and high-precision measurements may fall short. Based on the required accuracy, data volume, and computation speed, the type is determined and the conversion points are tested.
10. No.004: Rounding Error
Practical Use
The result differs depending on whether you round the cost of each part into 1 yen increments and then add it up, or if you round it after the total. The rules for quotation, standard cost, and billing should be unified down to the calculation order.
Model and Method
If we set the rounding operation to , then generally,
Additionally, we distinguish between approximate errors in binary floating-point representations and the use of decimal rounding as a business rule.
Check with Python
line_cost = factory_df["quantity"] * factory_df["unit_cost_yen"]
rounding_comparison = pd.Series(
{
"by itemized item1After rounding, total": np.round(line_cost, 0).sum(),
"After adding the total without rounding,1rounded": np.round(
line_cost.sum(), 0
),
}
)
rounding_comparison.to_frame("Total cost (yen)").assign(
difference_from_the_standard=lambda x: x["Total cost (yen)"] - x.iloc[1, 0]
)
| Total cost (yen) | difference_from_the_standard | |
|---|---|---|
| by itemized item1After rounding, total | 13856809.0 | 13.0 |
| After adding the total without rounding,1rounded | 13856796.0 | 0.0 |
Interpreting the Results
The difference is not necessarily a misimplementation, but rather a difference in the rounding conventions. However, for bulk invoices, the differences accumulate. Specify the “rounding units, methods, and timing” in the requirements definition, and prepare examples of reconciliation with the accounting system.
11. No.005: Cancellation
Practical Use
Subtracting nearly equal values cancels shared leading digits and can expose errors already present in the inputs. This matters when computing small displacements or differences between large energy totals.
Model and Method
When and are close, input errors can become large relative to . Algebraically stable formulas, subtracting a reference before reducing precision, and higher-precision data types can help.
Check with Python
reference64 = np.float64(100_000_000.0)
measured64 = np.float64(100_000_000.125)
reference32, measured32 = np.float32(reference64), np.float32(measured64)
pd.DataFrame(
{
"type": ["float64", "float32"],
"reference value": [reference64, reference32],
"Measurement value": [measured64, measured32],
"difference": [measured64 - reference64, measured32 - reference32],
}
)
| type | reference value | Measurement value | difference | |
|---|---|---|---|---|
| 0 | float64 | 100000000.0 | 100000000.125 | 0.125 |
| 1 | float32 | 100000000.0 | 100000000.000 | 0.000 |
Interpreting the Results
The two inputs round to the same value when converted to float32, losing the difference of 0.125 before subtraction. This example shows how input rounding affects a small difference; the subtraction itself introduces no further error. Subtracting the reference before converting to lower precision preserves the displacement.
12. No.006: Loss of Small Addends
Practical Use
If you add a very small value to a large cumulative value, the small value will fall below the representable digit and will not be reflected in the addition result. This occurs when accumulating small increments from high-speed sensors over a long period.
Model and Method
Let be the gap from a positive floating-point value to the next larger representable value. With rounding to nearest, gives . Midpoint cases depend on the tie-breaking rule. Summing small values together first or using compensated summation can reduce this loss.
Check with Python
values = np.concatenate(([1e16], np.ones(1_000_000)))
naive_sum = values.sum()
small_first_sum = values[::-1].sum()
import math
compensated_sum = math.fsum(values.tolist())
pd.DataFrame(
{
"Methods": [
"From the large priceNumPyTotal",
"From low pricesNumPyTotal",
"math.fsum(Total compensation)",
],
"Total": [naive_sum, small_first_sum, compensated_sum],
"Difference from theoretical values": [
naive_sum - (1e16 + 1e6),
small_first_sum - (1e16 + 1e6),
compensated_sum - (1e16 + 1e6),
],
}
)
| Methods | Total | Difference from theoretical values | |
|---|---|---|---|
| 0 | From the large priceNumPyTotal | 1.0000000001e+16 | -12.0 |
| 1 | From low pricesNumPyTotal | 1.0000000001e+16 | 0.0 |
| 2 | math.fsum(Total compensation) | 1.0000000001e+16 | 0.0 |
Interpreting the Results
Even if the values are the same, the result will change depending on the order of addition. For key cumulative KPIs, units are properly scaled, stable aggregation methods are adopted, and tolerances for recounting are defined.
13. No.007: Overflow
Practical Use
Failure models including exponential functions, likelihood calculations, and incorrect unit conversion indicators can exceed the maximum value of the type and become inf. It also contaminates subsequent averages and optimization results.
Model and Method
The maximum finite value of float64 is about . In exponential calculation, methods such as calculating in the log domain rather than direct multiplication, verifying input ranges, and detecting anomalies with isfinite are effective.
Check with Python
growth_rates = np.array([700.0, 710.0, 720.0])
with np.errstate(over="ignore"):
direct = np.exp(growth_rates)
result_007 = pd.DataFrame(
{"index": growth_rates, "exp(x)": direct, "Finite value?": np.isfinite(direct)}
)
result_007
| index | exp(x) | Finite value? | |
|---|---|---|---|
| 0 | 700.0 | 1.0142320547e+304 | True |
| 1 | 710.0 | inf | False |
| 2 | 720.0 | inf | False |
Interpreting the Results
Simply removing warnings is not enough to address the issue. Verify input limits, units, and finiteness, and treat products or exponents as logarithmic values if you only compare them. Avoid quietly excluding inf as a missing value.
14. No.008: Underflow
Practical Use
Multiplying many small probabilities or likelihoods can return zero even when the mathematical result is positive. This can prevent an anomaly-detection model from comparing candidates.
Model and Method
The product of probabilities can be obtained using logarithms,
By converting the product to sum, it is less likely to exceed the expressible range and allows for maintenance of large and small comparisons.
Check with Python
probabilities = np.full(1_000, 0.01)
direct_probability = np.prod(probabilities)
log_probability = np.log(probabilities).sum()
pd.Series(
{
"direct product of probability": direct_probability,
"logarithmic probability": log_probability,
"Held as a finite logarithm": np.isfinite(log_probability),
}
).to_frame("value")
| value | |
|---|---|
| direct product of probability | 0.0 |
| logarithmic probability | -4605.1701859881 |
| Held as a finite logarithm | True |
Interpreting the Results
The direct product becomes zero, but the logarithmic probability can still be retained. In predictive maintenance and quality models, log-likelihood is used as the standard, distinguishing whether “0” is true zero or a numerical limit.
15. No.009: Machine Epsilon
Practical Use
Machine epsilon describes representable spacing near 1.0. It is not a universal tolerance for every comparison or every numerical scale.
Model and Method
Here, machine epsilon is the gap between 1 and the next larger representable value. np.finfo(np.float64).eps is . This differs from the smallest increment for which rounded addition gives . Use np.spacing(x) to inspect the local spacing for positive , and choose operational tolerances from measurement resolution and product specifications.
Check with Python
scale_values = np.array([1.0, 50.0, 1e8, 1e16])
pd.DataFrame(
{
"value x": scale_values,
"xThe interval to the next expression value in the neighborhood": np.spacing(
scale_values
),
"relative interval": np.spacing(scale_values) / scale_values,
}
).assign(float64_machine_epsilon=np.finfo(np.float64).eps)
| value x | xThe interval to the next expression value in the neighborhood | relative interval | float64_machine_epsilon | |
|---|---|---|---|---|
| 0 | 1.0000000000e+00 | 2.2204460493e-16 | 2.2204460493e-16 | 2.2204460493e-16 |
| 1 | 5.0000000000e+01 | 7.1054273576e-15 | 1.4210854715e-16 | 2.2204460493e-16 |
| 2 | 1.0000000000e+08 | 1.4901161194e-08 | 1.4901161194e-16 | 2.2204460493e-16 |
| 3 | 1.0000000000e+16 | 2.0000000000e+00 | 2.0000000000e-16 | 2.2204460493e-16 |
Interpreting the Results
The absolute spacing widens as the value increases. For comparison, it is important to set relative and absolute tolerances for np.isclose according to the application, and not to confuse machine accuracy with process capability.
16. No.010: Evaluation of Numerical Errors
Practical Use
An error expressed in millimeters answers a different question from an error expressed as a percentage of the reference. Choose metrics and acceptance limits appropriate to quality, cost, or simulation validation.
Model and Method
For true value and approximate value , the absolute error and relative error are
If the true value is near zero, the relative error becomes unstable, so use the absolute tolerance. If there is uncertainty in the reference value itself, that uncertainty is included in the evaluation.
Check with Python
raw = factory_df["measurement_raw_mm"].to_numpy()
displayed = factory_df["measurement_display_mm"].to_numpy()
abs_error = np.abs(displayed - raw)
rel_error = abs_error / np.abs(raw)
error_summary = pd.Series(
{
"maximum_absolute_error (mm)": abs_error.max(),
"mean absolute error (mm)": abs_error.mean(),
"Maximum relative error (%)": 100 * rel_error.max(),
"Half the display resolution (mm)": 0.0005,
}
)
display(error_summary.to_frame("value"))
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.hist(abs_error * 1_000, bins=20, color="#2878B5", edgecolor="white")
ax.axvline(0.5, color="#C82423", linestyle="--", label="Half the display resolution")
ax.set_title("Rounding error at a display resolution of 0.001 mm")
ax.set_xlabel(r"absolute_error ($\mu$m)")
ax.set_ylabel("Number of measurements")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
| value | |
|---|---|
| maximum_absolute_error (mm) | 0.0004999639 |
| mean absolute error (mm) | 0.0002556658 |
| Maximum relative error (%) | 0.0009999378 |
| Half the display resolution (mm) | 0.0005000000 |

Interpreting the Results
The absolute error from rounding is, in theory, at most half the display increment of 0.001 mm. The operational requirements determine whether this error is sufficiently small for a tolerance ± 0.010 mm, or whether products near the judgment boundary should be remeasured. Even if the relative error is small, if you cross the pass/fail boundary, you can’t ignore it.
17. Lessons from the Examples
- Data types are design items: Determined not only by storage capacity but also by measurement resolution, cumulative period, and calculation content.
- The rounded rules are for business purposes.: Standardize not only the number of digits but also the method and timing.
- The correctness of the formula and the stability of the calculation are different: Even if mathematically equivalent, the results differ with finite precision.
- Do not mechanically exclude outliers: Check whether
inf, 0, andNaNindicate numerical limits. - Connecting errors to judgment criteria: Absolute and relative errors, measurement uncertainty, tolerances, and losses are evaluated together.
18. Putting the Methods into Practice
- Inventory data types and units among PLCs, sensors, databases, and BIs
- Define specifications for accuracy, rounding, missing values, finiteness, and tolerance for each key KPI
- Prepare automated tests including boundary values, large and small values, and addition order
- Record source data, conversion history, library versions, and random seed numbers to ensure reproducibility.
- Quality assurance, accounting, production technology, and IT are all confirmed to be accepted using the same calculation example
If you want to start small, it’s realistic to select three KPIs directly related to pass/fail, billing, and equipment downtime, and visualize the current calculation path and error budget.
19. Summary
Floating-point numbers are convenient but represent finite-precision representations. By understanding rounding errors, cancellation, loss of small addends, overflow, and underflow, and distinguishing between machine epsilon and operational tolerances, calculation results can be safely used for decision-making. What matters is not just increasing the number of digits, but designing data representation, stable computation, and verification criteria as a unified whole.
20. Business Inquiries
At Surikobo, we offer consultations not only on manufacturing data analysis, numerical simulation, mathematical optimization, and AI implementation, but also on reviewing the calculation accuracy of existing KPIs and conducting in-house training. We organize the characteristics of field data and decision-making flows, supporting everything from PoC to operational design.
📩 Contact Us: www.surikobo.co.jp/contact
Contact us to discuss your project.