Lesson 1.4 · I Geometry
Computing with floating-point numbers
What it's about: How precisely a computer computes, what this means for a model, and which rules knotflow follows so that rounding errors never lead to broken files.
In short: The precision is enough for any printer, by many orders of magnitude. Errors do not arise from too few digits, but from how things are computed: from computations in which large numbers almost cancel each other out, and from decisions ("is the point to the left or right?") that depend on the last digit. For models, a few simple rules follow.
What a floating-point number is
Every number in knotflow is a floating-point number
with 64 bits (in Rust f64, in C double): about
15 significant digits and an exponent that indicates where the decimal
point is. As in 6.02·10²³, the precision is relative:
the 16th digit is about 10⁻¹⁶ mm at 1 mm, and already 10⁻¹⁰ mm at 1 km.
The smallest relative distance between two neighbouring numbers is
called machine epsilon ε; for f64 ε = 2⁻⁵²
≈ 2.2·10⁻¹⁶. Every single operation gives the correct result, rounded to
the nearest representable number.
A 3D printer resolves about 0.01 mm. For a pot of 500 mm, you therefore need about 5 significant digits; there are 15.
STL files store points in 32 bits
(f32), with about 7 significant digits. That is enough on
the print bed too, but with less to spare. What this grid cannot resolve
falls together when written: at 32 mm neighbouring f32
numbers are 0.000004 mm apart, and an edge of 0.0000006 mm has only one
point left there. knotflow takes such edges out of the mesh before
writing: their ends become one corner and the two triangles along them
go. The file then has a few triangles fewer than kf render
reports for the mesh in memory.
Rules for models
- Models belong near the origin. Because precision is relative, it becomes coarser with the distance from the origin. In the STL file, neighbouring numbers at a distance of 1 km are 0.06 mm apart, at 1000 km 64 mm. knotflow computes internally with 64 bits and only rounds when writing; shapes further than 10⁹ mm (1000 km) from the origin are an error.
- Do not test computed numbers for equality.
0.1 + 0.2 == 0.3is false because neither 0.1 nor 0.2 is exactly representable; the sum is0.30000000000000004. knotflow shows numbers in the shortest form that results in exactly the same number when re-read, and thus does not hide such remainders. If you need to compare, compare with a threshold:abs(a - 0.3) < 1e-9. - Angles in degrees.
sinandcoswork in degrees and are exact at all multiples of 30° and 45°:cos(90)is 0,cos(60)is 0.5. With radians this would not work, because π/2 is not a representable number;cos(π/2)would be 6·10⁻¹⁷. Rotations of 90° and circular arcs over quarters thus land exactly on the axes. - Numbers are always finite. A computation that would
give infinity or "not a number" (NaN), such as
1 / 0or10 ^ 400, is immediately an error, with the position in the model. Otherwise, a NaN would pass silently through all steps into the file. - Tolerances are specified, not hidden. Where
knotflow must approximate, the limit is stated: parallel curves and
curves of intersection lie at most 0.0001 mm away from the exact shape,
the triangles of the file at most by the tolerance (
--tol, otherwise 0.01 mm; handbook, chapter 13). - Same model, same file. The browser and the command line compute bit for bit the same and write byte-identical files. An STL can therefore be compared with an earlier one, and a difference means that the model has changed.
The language's rules about numbers, and why, are in Lesson 2.3 (section 2).
How knotflow computes internally
Behind these rules are five principles for the core. The experiments in the deeper part show what happens without them.
- Stable ways of computing. Curves are evaluated via their control points (Lesson 1.2), never through multiplied-out polynomials; derivatives of curves and surfaces are computed exactly, not estimated from two close points (experiments 1 and 2).
- Shared points computed once. Where two surfaces share an edge, each point of the edge is computed once and used by both sides, instead of computing it twice and comparing it afterwards. Then the mesh is closed, however things were rounded (experiment 4).
- Exact decisions. Whether a point lies to the left or right of a line is computed so that the sign is always right (experiment 5).
- 64 bits everywhere, 32 bits only in the file (and for the graphics card; experiment 3).
- Mathematical functions of its own. Sine, cosine,
power and logarithm come from a library of its own (
libm, viacrates/geom/src/math.rs), not from the operating system or browser: they are allowed to round differently in the last digit, and then the files would no longer be byte-identical.
How it is checked
A script computes all examples in the browser build (WebAssembly) and
with kf and compares the files byte by byte. Every exported
shape is checked for a closed mesh, and kf check file.stl
reads a finished STL like a slicer and compares the corner points
exactly. The numbers from the experiments below come from real runs of
cargo run -p geom --example numerik (code in
crates/geom/examples/numerik.rs).
In depth: five experiments
Two terms first:
- Cancellation: Subtract two almost equal numbers, and the leading digits cancel; what is left are the trailing ones, which already carry rounding errors. 1.0000000000000002 − 1.0000000000000000 gives a number whose only digit may be noise.
- Condition: how much a computation magnifies small errors in its input. A condition of 10⁸ means: an error in the 16th digit becomes one in the 8th.
Experiment 1: The representation decides
The same Bézier curve is evaluated twice. Once with de Casteljau via the control points (Lesson 1.2), mathematically speaking in the Bernstein basis. Once as a multiplied-out polynomial a₀ + a₁t + … + aₙtⁿ (monomial basis), efficiently evaluated with the Horner scheme (a₀ + t·(a₁ + t·(a₂ + …))). Mathematically, both are the same function. All control points lie between −1 and 1.
| Degree | largest coefficient aₖ | max. deviation on [0, 1] |
|---|---|---|
| 3 | 2.8 | 6.7·10⁻¹⁶ |
| 10 | 1.8·10³ | 1.0·10⁻¹² |
| 20 | 2.1·10⁸ | 7.1·10⁻⁸ |
| 25 | 4.7·10¹⁰ | 3.4·10⁻⁵ |
| 30 | 5.8·10¹² | 6.9·10⁻³ |
At degree 30, only two to three digits are correct. The coefficients are huge and have alternating signs, but their sum lies between −1 and 1: terms of magnitude 10¹² almost completely cancel out, cancellation in its pure form. The condition is approximately Σ|aₖtᵏ| / |f(t)|, and ε is amplified by this factor.
De Casteljau and de Boor, in contrast, only form convex combinations: (1−a)·A + a·B with a between 0 and 1, that is, points between A and B. In this process, nothing is subtracted that is almost equal, and the error remains in the order of magnitude n·ε·max|Pᵢ|. This is the main reason why CAD computes with control points and not with polynomial coefficients.
Experiment 2: Differentiating with two close points
A derivative can be approximated as a difference quotient (C(t+h) − C(t−h)) / 2h. How well does that work, depending on h? Measured against a circle with radius 10, compared with the exact derivative:
h | relative error
1e-1 | 6.9e-2 ###############################
1e-2 | 1.0e-3 ############################
1e-3 | 1.0e-5 ########################
1e-4 | 1.0e-7 ####################
1e-5 | 1.0e-9 ################
1e-6 | 4.1e-11 ############# ← Optimum
1e-7 | 1.0e-10 ##############
1e-8 | 8.3e-10 ###############
1e-10 | 1.1e-7 ####################
1e-12 | 2.4e-5 ########################
1e-14 | 2.4e-3 ############################
The error has two parts:
- The truncation error (because the formula is only an approximation) is about h²/6 · |C'''| and shrinks as h shrinks.
- The rounding error is about ε·|C| / h and grows as h shrinks: C(t+h) and C(t−h) are then almost equal, and their difference is cancellation.
The minimum is at h ≈ ε^(1/3) ≈ 6·10⁻⁶, and even there only about 10
digits are correct. knotflow therefore computes derivatives exactly: the
derivative of a B-spline is again a B-spline, one degree lower. The
difference quotient is used in the test as an independent check, with a
bound to match. Derivatives are taken numerically only where there is no
formula: the equations of solve (Lesson 3.11) and the shift
d · n of a offset surface (Lesson 3.8), each with a step that fits the
size.
Experiment 3: Far from the origin
A circle with 5 mm radius is moved further and further from the origin. The radius error in 64 bits and the distance of neighbouring 32-bit numbers at this position are measured, that is, the grid that the STL file rounds to.
| Distance | radius error f64 |
f32 grid there |
|---|---|---|
| 0 | 1.8·10⁻¹⁵ mm | 1.2·10⁻⁷ mm |
| 1 m | 4.0·10⁻¹³ mm | 6.1·10⁻⁵ mm |
| 1 km | 4.2·10⁻¹⁰ mm | 6.2·10⁻² mm |
| 1000 km | 4.7·10⁻⁷ mm | 64 mm |
64 bits are enough for any printer even 1000 km away; 32 bits are not, already at 1 km. Part of the measured "error", by the way, comes from the measuring itself: the radius is |P − centre|, the difference of two large, almost equal numbers.
Experiment 4: The same point in two ways
This experiment explains open edges in triangle meshes, on which models fail in programs that cut into triangles early.
a) The seam of a surface of revolution. Step on by 360°/n, n times, and you should be back at the start:
n = 3 … 200 (198 cases): End point ≠ Start point in f64: 198, in f32: 198
Example n = 7: sin(7 · 2π/7) · 75 = -1.8e-14
In no case do you get back exactly, not in 32 bits either: 1.8·10⁻¹⁴ can be stored there too, and it is not 0. The cause is in the input already: 2π is not a representable number, so sin(2π) ≈ −2.4·10⁻¹⁶.
b) Repeated rotation. "Copy, rotate by 1°, copy again..." results in a different point after k steps than "rotate by k° once": 359 of 360 points deviate by at most 10⁻¹² mm. Geometrically that does not matter; for a test of equality it is a different point.
c) A point at 90°, computed as r · cos(π/2), has x = 4.6·10⁻¹⁵ instead of 0 for r = 75, because π/2 is not a representable number. knotflow's circle hits the axis exactly: its control points are built from exact quarters, and angles in degrees are exact at 90° (rule 3). That helps at these places, but does not replace the following principle: at 37°, no way is exact.
The lesson: Do not create the same points twice in the first place, instead of comparing them afterwards. A mesh stores every vertex once, and the triangles refer to it by a number (an index). At the seam of the surface of revolution, the last piece simply uses the numbers of the first. So the mesh is closed, whatever the floating-point numbers do.
Comparing with a threshold ("equal if the distance is smaller than 10⁻⁹") is only a stopgap, because this equality is not transitive: A ≈ B and B ≈ C, but not necessarily A ≈ C.
Experiment 5: Left or right?
Many methods in geometry, such as cutting a surface into triangles, intersections or "is the point inside the polygon?", rely on a single question: is point a to the left of, to the right of or on the line b → c? The answer is given by the sign of a small expression (a determinant):
orient(a, b, c) = (b.x − a.x)·(c.y − a.y) − (b.y − a.y)·(c.x − a.x)
The experiment is a well-known example from the literature (Kettner et al.): A 32×32 grid of points a = (0.5 + i·u, 0.5 + j·u) with u = 2⁻⁵³, that is, the smallest possible steps near 0.5, is tested against the line (12, 12) → (24, 24). The right answer is a clean diagonal of zeros between "+" (left) and "−" (right):
naive (double) exact (Shewchuk)
00000000000000000+++++++00000000 +++++++++++++++++++++++++++++++0
00000000000000000+++++++00000000 ++++++++++++++++++++++++++++++0-
…
000000000000000000000000-------- +++++++++++++++++++++++0--------
+++++++++00000000000000000000000 ++++++++++++++++0---------------
000000000--------000000000000000 ++++++++0-----------------------
000000000--------000000000000000 0-------------------------------
736 of 1024 decisions are wrong. Computed naively, points appear "on the line" that are beside it, and there are even "+" islands on the "−" side. The determinant is the difference of two almost equal products, so again cancellation, only now the noise decides a sign, and with it a branch in the program.
This is more dangerous than a small numerical error. A method that hears "left" once and "right" later for the same position can cause triangles to overlap, enter an infinite loop or crash. Many crashing booleans in CAD programs have this cause.
The cure is robust predicates after Jonathan Shewchuk (1997); a predicate is a computation whose result is a decision. First a quick computation with ordinary floating-point numbers, together with a bound on its error. If the result is clearly larger than the bound, the sign is certain; that is the usual case. Only when it is close does the computation go on exactly, with floating-point expansions: A number is then represented as a sum of several floating-point numbers that together yield exactly the correct value without rounding. This costs almost nothing on average, because the exact path is rarely needed.
knotflow needs this where it cuts surfaces with holes or curves of
intersection into triangles (Lessons 3.5 and 3.7). The library
spade, which it uses for this, computes with exactly these
predicates; in the experiment they come from the library
robust.
Exercises
The experiments run with
cargo run -p geom --example numerik (all of them) or
… -- 5 (only experiment 5).
- In the language: what do
0.1 * 3,0.3 / 0.1andsqrt(2) * sqrt(2)give? Which of them would be a trap as a list index? - Experiment 1: raise the degree to 35 or 40. From when on is the monomial form worthless?
- Experiment 2: replace the central difference quotient by the one-sided one (C(t+h) − C(t)) / h. Where is the optimum now, and why at about √ε?
- Experiment 5: move the grid from 0.5 to 0.25, or change b and c. How does the pattern change?
- To think about: why is cos(2π) in
f64exactly 1 all the same, but sin(2π) not exactly 0? (Hint: the Taylor expansion around the true value 2π, and how far the representable number is from 2π.)