Algorithmcore
Arc length table
Also called arc length lookup table.
Tabulate the arc length of a parametric curve at sample parameters, then invert it by binary search, linear interpolation and optional Newton steps, to move along a path at a given speed.
- Time
- Θ(m) buildO(log m + r) query
- Space
- Θ(m) extra
- Where
- m = the number of table intervals; r = the number of Newton steps per query
- Model
- Real RAM
- Properties
- deterministicnot exactofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
An arc length table lets an animation move a point along a curve by distance instead of by parameter. Most curves used in animation, such as Bezier and Catmull-Rom curves, have no closed form for the arc length , and the parameter does not grow at a constant rate with the distance. The table stores at sample parameters, computed by adaptive Gauss-Legendre quadrature. A query for a distance finds the right interval by binary search, interpolates linearly, and can refine the result with Newton steps. Guenter and Parent (1990) gave this scheme for animation paths.
In plain words
A curve in a drawing program has a parameter that runs from 0 to 1, but equal steps of the parameter do not give equal steps along the curve. Where the control points are close, the curve is slow; where they are far apart, it is fast. To move a camera at a steady speed, you need the parameter for a given distance. The table measures the length of the curve at many evenly spaced parameter values, once. Later, to find where the distance 3.7 is, you look in the table for the two entries around 3.7 and take the value in between. If you need more accuracy, a few correction steps polish the answer.
The problem
The input is a differentiable curve , given by a function for its derivative , a table size , and a tolerance . The build step outputs the sample parameters , , and the arc lengths for . A query takes a distance and outputs with . The theory of the arc length function and of the arc length parametrization is on the page arc length parametrization.
The algorithm
is the five-point Gauss-Legendre rule for , exact for polynomials of degree 9.
BUILD(c', a, b, m, ε) ▷ returns the table (u_k, s_k)- 1
h ← (b - a) / m; u₀ ← a; s₀ ← 0 - 2
for k ← 1 to m do - 3
uₖ ← a + k h - 4
sₖ ← sₖ₋₁ + AGL(|c'|, uₖ₋₁, uₖ, ε / m) AGL(f, x, y, ε) ▷ adaptive Gauss-Legendre quadrature- 5
W ← G₅(f, x, y) - 6
L ← G₅(f, x, (x + y)/2); R ← G₅(f, (x + y)/2, y) - 7
if |L + R - W| ≤ ε then return L + R - 8
return AGL(f, x, (x + y)/2, ε/2) + AGL(f, (x + y)/2, y, ε/2) QUERY(s*, r) ▷ r Newton steps- 9
find k with sₖ ≤ s* ≤ sₖ₊₁ by binary search - 10
u ← uₖ + h (s* - sₖ) / (sₖ₊₁ - sₖ) - 11
repeat r times: u ← u - (sₖ + G₅(|c'|, uₖ, u) - s*) / |c'(u)| - 12
return u
Lines L1 to L4 fill the table, one interval at a time, so the cost grows linearly with . Lines L5 to L8 split an interval in half until the two halves agree with the whole to the tolerance. Line L9 is a binary search on the sorted lengths. Line L10 is the linear interpolation of the inverse function. Line L11 is Newton's method on , with ; the length from to comes from one Gauss-Legendre rule on a short interval. The implementation also clamps to after each Newton step and stops if the speed is 0.
Example
Take the parabola on , with the speed , and . The exact total length is .
- Lines L1 to L4 give and . Each entry agrees with the closed form to .
- Query . Line L9 finds , since .
- Line L10: .
- The exact answer is . One Newton step gives , with the error , and a second step gives , with the error .
The worst error of line L10 alone over is for , for , for and for : each doubling of divides the error by 4.
Correctness
The speed is not negative, so the table values do not decrease, and the binary search of line L9 finds a valid interval. If the speed is positive, is strictly increasing and has a differentiable inverse .
The error of a table entry is the sum of the quadrature errors of its intervals. The five-point rule on an interval of length has the error , so for a smooth curve the table is accurate to roundoff with a moderate . The stopping test of line L7 estimates the error by the difference of two rules; it is not a bound, and a curve with a sharp feature inside one interval can fool it.
The linear interpolation of line L10 is the linear interpolant of the inverse function on . Its error is at most . With , the error is , of the second order in the sample spacing.
Newton's method on converges quadratically near the root when is bounded away from 0: the new error is at most times the square of the old one. Starting from an guess, one step gives and two steps , until the quadrature error of line L11 dominates. The proof gives the details.
Proof: The arc length table gives a valid interval, a second order inverse and quadratic Newton refinementfull
We use the notation of the page. The curve is on , and its speed satisfies . Then is with and , and it has a inverse on with and . We first assume that the table is exact, , and treat the quadrature error at the end.
The search
Lemma 1. The values are strictly increasing, and for each line L9 finds with .
Proof. . A sorted sequence with has such an index, and binary search finds it in comparisons.
The linear inverse
Lemma 2. Let be the value of line L10. Then .
Proof. On , the inverse function satisfies and . Line L10 is the linear interpolant of through these two points. The error of linear interpolation of a function on an interval of length is at most . Here , and .
So the error is . If is constant, and line L10 is exact.
Newton refinement
Lemma 3. Let and for the current value in . One Newton step gives a new error with .
Proof. Write . By Taylor's theorem, for some between and . So .
Clamping to does not increase the error, because is in this interval. With the start error of Lemma 2, one step gives and two steps .
The quadrature error
Lemma 4. If each call of AGL on the interval returns its integral with the error , then for every . If , the value of lines L9 and L10 differs from the value with the exact table by at most .
Proof. The first claim is the triangle inequality on the sum of line L4. Let and be the piecewise linear functions of through the exact and the computed table values. Lines L9 and L10 solve , and the exact table gives the root of . On each interval, is a convex combination of two end differences, so . The slope of on an interval is at least . A function with this slope that is within of reaches within divided by the slope of the root of .
The five-point Gauss-Legendre rule on an interval of length has the error for a integrand, so for a smooth curve is far below the interpolation error of Lemma 2. The stopping test of line L7 compares two estimates and is a heuristic, not a bound; Lemma 4 holds with the true errors .
Complexity
The build step calls AGL times. For a smooth curve and a fixed tolerance, the recursion stops after a bounded number of splits, so the build costs evaluations of the speed. For a curve with a corner or a cusp the recursion goes deeper near the bad point, and the implementation caps its depth. The table takes space. A query costs for the binary search and for each Newton step, five speed evaluations for and one for . If the queries come in increasing order of , as in an animation that moves forward, a pointer that walks through the table replaces the binary search, at amortized cost per query.
Properties
- Second order in the spacing. The inverse by linear interpolation has the error ; doubling divides it by 4, as in the example.
- Exact for constant speed. On a curve with a constant speed, such as an arc of a circle, is linear in and line L10 is exact.
- Monotone queries. Without Newton steps, the returned is a monotone function of , so the point never moves backwards.
- A speed that jumps. The piecewise linear inverse has a derivative that jumps at the table entries, by , so the speed of the moving point jumps slightly there. Newton steps remove this to the accuracy of the iteration.
- Independence of the motion. The table depends only on the curve. One table serves every speed curve, such as each ease curve of a shot.
Variants and improvements
- Newton with full quadrature. Find by Newton iteration on , with adaptive quadrature for each value of . The table then only gives the start value and the length up to .
- Uniform in distance. Resample the table so that the lengths, not the parameters, are evenly spaced. Then line L9 becomes a division, at the cost of an inverse at build time.
- Polyline tables. Sum the chord lengths of a fine polyline. It is simple, but its error is for chords, much worse than Gauss-Legendre quadrature.
- Higher-order inverse. Interpolate with a cubic Hermite segment, using at the table entries. The error is then with no iteration.
- Arc length of a spline. For a spline, build one table per segment, or one table with entries at the knots, so that no interval contains a knot.
When to use it
Use an arc length table to move a camera, a character or an object along a path at a speed that the animator controls, with the distance from an ease curve or from a time scaling. It also places objects at equal distances along a curve, such as the posts of a fence or the dashes of a line. If the curve has a known arc length, as a line or a circle does, use the closed form.
Pitfalls
- Points where the speed is 0. At a cusp or at repeated control points, , the inverse function is not differentiable, and Newton's method divides by 0. Stop the iteration there, or keep in the interval of line L9.
- Too few entries. The error of line L10 grows with the square of the spacing and with the variation of the speed. Check it on the curve, not only on the total length.
- A tolerance that is too tight. The quadrature cannot be more accurate than the roundoff of the sum of the lengths. A tolerance below about times the length only makes the recursion deeper.
- Changing curves. If the control points move, the table is wrong. Rebuild it, or tabulate only the segments that changed.
- Arc length is not timing. The table gives a constant speed only if grows linearly with time. Easing and pauses come from the curve that gives .
Implementations
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/arc-length-table/. The authors are listed in prov/JYYH1E.jsonl.
"""Arc length table of a parametric curve, and its inverse.
The table stores the parameters u_k = a + k h, h = (b - a) / m, and the arc
lengths s_k from u_0 to u_k, computed by adaptive five-point Gauss-Legendre
quadrature of the speed |c'(u)|. A query takes a distance s* in [0, s_m],
finds the interval by binary search, interpolates linearly, and can refine
the result by Newton steps on s(u) - s*.
"""
import bisect
import math
# Five-point Gauss-Legendre nodes and weights on [-1, 1].
_GL_X = (
0.0,
-0.5384693101056831,
0.5384693101056831,
-0.9061798459386640,
0.9061798459386640,
)
_GL_W = (
0.5688888888888889,
0.4786286704993665,
0.4786286704993665,
0.2369268850561891,
0.2369268850561891,
)
def gauss5(f, x, y):
"""Return the five-point Gauss-Legendre estimate of the integral of f on [x, y]."""
c = (x + y) / 2.0
r = (y - x) / 2.0
return r * sum(w * f(c + r * t) for t, w in zip(_GL_X, _GL_W))
def adaptive_gauss(f, x, y, eps, whole=None, depth=0):
"""Return the integral of f on [x, y] to about the absolute error eps."""
if whole is None:
whole = gauss5(f, x, y) # @line L5
mid = (x + y) / 2.0
left = gauss5(f, x, mid) # @line L6
right = gauss5(f, mid, y)
if abs(left + right - whole) <= eps or depth >= 40: # @line L7
return left + right
return adaptive_gauss(f, x, mid, eps / 2.0, left, depth + 1) + adaptive_gauss( # @line L8
f, mid, y, eps / 2.0, right, depth + 1
)
def speed_of(dcurve):
"""Return the function u -> |c'(u)| for a derivative function dcurve."""
return lambda u: math.sqrt(sum(x * x for x in dcurve(u)))
class ArcLengthTable:
"""Arc length table of a curve given by its derivative c'(u) on [a, b]."""
def __init__(self, dcurve, a, b, m, eps=1e-12):
if m < 1 or not b > a:
raise ValueError("need m >= 1 and b > a")
self.speed = speed_of(dcurve)
self.a, self.b, self.m = a, b, m
self.h = (b - a) / m # @line L1
self.u = [a]
self.s = [0.0]
for k in range(1, m + 1): # @line L2
uk = a + k * self.h # @line L3
self.s.append(self.s[-1] + adaptive_gauss(self.speed, self.u[-1], uk, eps / m)) # @line L4
self.u.append(uk)
def length(self):
"""Return the total arc length s_m."""
return self.s[-1]
def arc_length(self, u):
"""Return s(u), from the table and one Gauss-Legendre rule on the last part."""
k = min(max(int((u - self.a) / self.h), 0), self.m - 1)
return self.s[k] + gauss5(self.speed, self.u[k], u)
def param(self, s_star, newton=0):
"""Return the parameter u with s(u) = s_star, with optional Newton steps."""
s_star = min(max(s_star, 0.0), self.s[-1])
k = bisect.bisect_right(self.s, s_star) - 1 # @line L9
k = min(max(k, 0), self.m - 1)
ds = self.s[k + 1] - self.s[k]
u = self.u[k] + (self.h * (s_star - self.s[k]) / ds if ds > 0.0 else 0.0) # @line L10
for _ in range(newton):
v = self.speed(u)
if v == 0.0:
break
u = u - (self.s[k] + gauss5(self.speed, self.u[k], u) - s_star) / v # @line L11
u = min(max(u, self.u[k]), self.u[k + 1])
return u # @line L12
test_arc_length_table.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/arc-length-table/. The authors are listed in prov/JYYH1E.jsonl.
import math
import random
import pytest
from arc_length_table import ArcLengthTable, adaptive_gauss, gauss5
def parabola_d(u):
return (1.0, 2.0 * u)
def parabola_s(u):
# Closed form of the arc length of c(u) = (u, u^2) from 0 to u.
return u * math.sqrt(1.0 + 4.0 * u * u) / 2.0 + math.asinh(2.0 * u) / 4.0
def invert(f, target, lo, hi):
# Reference inverse of an increasing function by bisection.
for _ in range(200):
mid = (lo + hi) / 2.0
if f(mid) < target:
lo = mid
else:
hi = mid
return (lo + hi) / 2.0
def test_gauss5_is_exact_for_degree_nine(rng=random.Random(1)):
for _ in range(10):
c = [rng.uniform(-1, 1) for _ in range(10)]
f = lambda x: sum(ck * x**k for k, ck in enumerate(c))
x, y = rng.uniform(-2, 0), rng.uniform(0, 2)
exact = sum(ck * (y ** (k + 1) - x ** (k + 1)) / (k + 1) for k, ck in enumerate(c))
assert abs(gauss5(f, x, y) - exact) < 1e-12
def test_adaptive_gauss_on_a_hard_integrand():
val = adaptive_gauss(lambda x: math.sqrt(x), 0.0, 1.0, 1e-10)
assert abs(val - 2.0 / 3.0) < 1e-9
def test_parabola_length_and_table_values():
t = ArcLengthTable(parabola_d, 0.0, 1.0, 16)
assert abs(t.length() - (2 * math.sqrt(5) + math.asinh(2)) / 4) < 1e-12
assert abs(t.length() - 1.4789428575445975) < 1e-12
for uk, sk in zip(t.u, t.s):
assert abs(sk - parabola_s(uk)) < 1e-12
for k in range(101):
assert abs(t.arc_length(k / 100) - parabola_s(k / 100)) < 1e-10
def test_linear_inverse_error_is_second_order():
errs = []
for m in (8, 16, 32, 64):
t = ArcLengthTable(parabola_d, 0.0, 1.0, m)
worst = 0.0
for j in range(401):
s = t.length() * j / 400
worst = max(worst, abs(t.param(s) - invert(parabola_s, s, 0.0, 1.0)))
errs.append(worst)
for e0, e1 in zip(errs, errs[1:]):
assert 3.0 < e0 / e1 < 5.0
assert errs[1] < 1e-3
def test_newton_refinement(rng=random.Random(2)):
t = ArcLengthTable(parabola_d, 0.0, 1.0, 8)
for _ in range(200):
s = rng.uniform(0.0, t.length())
ref = invert(parabola_s, s, 0.0, 1.0)
e0 = abs(t.param(s) - ref)
e1 = abs(t.param(s, newton=1) - ref)
e2 = abs(t.param(s, newton=2) - ref)
assert e1 <= max(10 * e0 * e0, 1e-12)
assert e2 < 1e-11
def test_against_a_fine_polyline(rng=random.Random(3)):
# A random planar cubic Bezier curve; the reference is a polyline of 20000 chords.
p = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(4)]
def point(u):
b = ((1 - u) ** 3, 3 * u * (1 - u) ** 2, 3 * u * u * (1 - u), u**3)
return tuple(sum(bk * pk[i] for bk, pk in zip(b, p)) for i in range(2))
def deriv(u):
b = (-3 * (1 - u) ** 2, 3 * (1 - u) ** 2 - 6 * u * (1 - u), 6 * u * (1 - u) - 3 * u * u, 3 * u * u)
return tuple(sum(bk * pk[i] for bk, pk in zip(b, p)) for i in range(2))
n = 20000
pts = [point(k / n) for k in range(n + 1)]
poly = [0.0]
for a, b in zip(pts, pts[1:]):
poly.append(poly[-1] + math.dist(a, b))
t = ArcLengthTable(deriv, 0.0, 1.0, 32)
assert abs(t.length() - poly[-1]) < 1e-6
for k in range(0, n + 1, 500):
assert abs(t.arc_length(k / n) - poly[k]) < 1e-6
u = t.param(poly[k], newton=2)
assert abs(u - k / n) < 1e-5
def test_constant_speed_curve_is_inverted_exactly():
r = 2.5
t = ArcLengthTable(lambda u: (-r * math.sin(u), r * math.cos(u)), 0.0, math.pi, 10)
assert abs(t.length() - r * math.pi) < 1e-12
for j in range(50):
s = t.length() * j / 49
assert abs(t.param(s) - s / r) < 1e-12
def test_param_is_monotone_and_clamped():
t = ArcLengthTable(parabola_d, 0.0, 1.0, 5)
prev = -1.0
for j in range(1001):
u = t.param(t.length() * j / 1000)
assert u >= prev
prev = u
assert t.param(-1.0) == 0.0 and abs(t.param(10.0) - 1.0) < 1e-15
with pytest.raises(ValueError):
ArcLengthTable(parabola_d, 1.0, 0.0, 4)
History
Guenter and Parent (1990) described the computation of the arc length of parametric curves for animation, with adaptive Gaussian quadrature of the speed, a table of lengths, and Newton iteration for the inverse. Parent's textbook (2012) presents the arc length table as the standard way to control the speed along a path. The quadrature rules come from Gauss and the error estimate by halving the interval is the usual one of adaptive quadrature.
References
- Brian Guenter and Richard Parent, Computing the arc length of parametric curves, IEEE Computer Graphics and Applications 10(3), 72-78, 1990, the whole paper (adaptive Gaussian quadrature of the speed, a table of arc lengths, and Newton iteration for the inverse)
- Rick Parent, Computer Animation, Algorithms and Techniques, 3rd edition, Morgan Kaufmann, 2012, Chapter 3, Section 3.2 (controlling the motion of a point along a curve: arc length tables, their inversion, and Gaussian quadrature)
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag JYYH1E Edit this page History Report an error Markdown