Algorithm Search⌘K

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
Properties
deterministicnot exactofflinerecursive

An arc length table lets an animation move a point along a curve c(u)c(u) 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 s(u)=∫au∣c′(x)∣ dxs(u) = \int_a^u |c'(x)|\,dx, and the parameter uu does not grow at a constant rate with the distance. The table stores ss at m+1m + 1 sample parameters, computed by adaptive Gauss-Legendre quadrature. A query for a distance s∗s^* 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 c:[a,b]→Rdc : [a, b] \to \mathbb{R}^d, given by a function for its derivative c′(u)c'(u), a table size mm, and a tolerance ε\varepsilon. The build step outputs the sample parameters uk=a+khu_k = a + kh, h=(b−a)/mh = (b - a)/m, and the arc lengths sk≈s(uk)s_k \approx s(u_k) for k=0,…,mk = 0, \dots, m. A query takes a distance s∗∈[0,sm]s^* \in [0, s_m] and outputs uu with s(u)≈s∗s(u) \approx s^*. The theory of the arc length function and of the arc length parametrization is on the page arc length parametrization.

The algorithm

G5(f,x,y)G_5(f, x, y) is the five-point Gauss-Legendre rule for ∫xyf\int_x^y f, exact for polynomials of degree 9.

  1. BUILD(c', a, b, m, ε) ▷ returns the table (u_k, s_k)
  2. 1h ← (b - a) / m; u₀ ← a; s₀ ← 0
  3. 2for k ← 1 to m do
  4. 3uₖ ← a + k h
  5. 4sₖ ← sₖ₋₁ + AGL(|c'|, uₖ₋₁, uₖ, ε / m)
  6. AGL(f, x, y, ε) ▷ adaptive Gauss-Legendre quadrature
  7. 5W ← G₅(f, x, y)
  8. 6L ← G₅(f, x, (x + y)/2); R ← G₅(f, (x + y)/2, y)
  9. 7if |L + R - W| ≤ ε then return L + R
  10. 8return AGL(f, x, (x + y)/2, ε/2) + AGL(f, (x + y)/2, y, ε/2)
  11. QUERY(s*, r) ▷ r Newton steps
  12. 9find k with sₖ ≤ s* ≤ sₖ₊₁ by binary search
  13. 10u ← uₖ + h (s* - sₖ) / (sₖ₊₁ - sₖ)
  14. 11repeat r times: u ← u - (sₖ + G₅(|c'|, uₖ, u) - s*) / |c'(u)|
  15. 12return u

Lines L1 to L4 fill the table, one interval at a time, so the cost grows linearly with mm. 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 g(u)=s(u)−s∗g(u) = s(u) - s^*, with g′(u)=∣c′(u)∣g'(u) = |c'(u)|; the length from uku_k to uu comes from one Gauss-Legendre rule on a short interval. The implementation also clamps uu to [uk,uk+1][u_k, u_{k+1}] after each Newton step and stops if the speed is 0.

Example

Take the parabola c(u)=(u,u2)c(u) = (u, u^2) on [0,1][0, 1], with the speed 1+4u2\sqrt{1 + 4u^2}, and m=4m = 4. The exact total length is 14(25+asinh⁡2)=1.478943\frac14(2\sqrt5 + \operatorname{asinh} 2) = 1.478943.

  • Lines L1 to L4 give u=(0,0.25,0.5,0.75,1)u = (0, 0.25, 0.5, 0.75, 1) and s=(0,0.26006,0.57390,0.97473,1.47894)s = (0, 0.26006, 0.57390, 0.97473, 1.47894). Each entry agrees with the closed form s(u)=12u1+4u2+14asinh⁡(2u)s(u) = \frac12 u\sqrt{1 + 4u^2} + \frac14\operatorname{asinh}(2u) to 10−1210^{-12}.
  • Query s∗=0.75s^* = 0.75. Line L9 finds k=2k = 2, since 0.57390≤0.75<0.974730.57390 \le 0.75 < 0.97473.
  • Line L10: u=0.5+0.25⋅(0.75−0.57390)/(0.97473−0.57390)=0.60984u = 0.5 + 0.25 \cdot (0.75 - 0.57390)/(0.97473 - 0.57390) = 0.60984.
  • The exact answer is u=0.6173865u = 0.6173865. One Newton step gives 0.61741450.6174145, with the error 2.8⋅10−52.8 \cdot 10^{-5}, and a second step gives 0.61738650.6173865, with the error 4⋅10−104 \cdot 10^{-10}.

The worst error of line L10 alone over [0,sm][0, s_m] is 1.9⋅10−31.9 \cdot 10^{-3} for m=8m = 8, 4.9⋅10−44.9 \cdot 10^{-4} for m=16m = 16, 1.2⋅10−41.2 \cdot 10^{-4} for m=32m = 32 and 3.0⋅10−53.0 \cdot 10^{-5} for m=64m = 64: each doubling of mm divides the error by 4.

Correctness

The speed ∣c′∣|c'| is not negative, so the table values sks_k do not decrease, and the binary search of line L9 finds a valid interval. If the speed is positive, ss is strictly increasing and has a differentiable inverse u(s)u(s).

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 ℓ\ell has the error (5!)411 (10!)3 ℓ11f(10)(ξ)\frac{(5!)^4}{11\,(10!)^3}\,\ell^{11} f^{(10)}(\xi), so for a smooth curve the table is accurate to roundoff with a moderate mm. 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 u(s)u(s) on [sk,sk+1][s_k, s_{k+1}]. Its error is at most 18(sk+1−sk)2max⁡∣u′′(s)∣\frac18 (s_{k+1} - s_k)^2 \max|u''(s)|. With sk+1−sk≤hmax⁡∣c′∣s_{k+1} - s_k \le h \max|c'|, the error is O(h2)O(h^2), of the second order in the sample spacing.

Newton's method on g(u)=s(u)−s∗g(u) = s(u) - s^* converges quadratically near the root when g′=∣c′∣g' = |c'| is bounded away from 0: the new error is at most max⁡∣s′′∣2min⁡∣s′∣\frac{\max|s''|}{2\min|s'|} times the square of the old one. Starting from an O(h2)O(h^2) guess, one step gives O(h4)O(h^4) and two steps O(h8)O(h^8), 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 cc is C2C^2 on [a,b][a, b], and its speed v(u)=∣c′(u)∣v(u) = |c'(u)| satisfies 0<vmin⁡≤v(u)≤vmax⁡0 < v_{\min} \le v(u) \le v_{\max}. Then s(u)=∫auvs(u) = \int_a^u v is C2C^2 with s′=vs' = v and s′′=v′s'' = v', and it has a C2C^2 inverse u(s)u(s) on [0,s(b)][0, s(b)] with u′=1/vu' = 1/v and u′′=−v′/v3u'' = -v'/v^3. We first assume that the table is exact, sk=s(uk)s_k = s(u_k), and treat the quadrature error at the end.

Lemma 1. The values s0,…,sms_0, \dots, s_m are strictly increasing, and for each s∗∈[0,sm]s^* \in [0, s_m] line L9 finds kk with sk≤s∗≤sk+1s_k \le s^* \le s_{k+1}.

Proof. sk+1−sk=∫ukuk+1v≥h vmin⁡>0s_{k+1} - s_k = \int_{u_k}^{u_{k+1}} v \ge h\,v_{\min} > 0. A sorted sequence with s0=0≤s∗≤sms_0 = 0 \le s^* \le s_m has such an index, and binary search finds it in O(log⁡m)O(\log m) comparisons. □\square

The linear inverse

Lemma 2. Let u^\hat u be the value of line L10. Then ∣u^−u(s∗)∣≤18h2vmax⁡2max⁡∣u′′∣≤h2vmax⁡2max⁡∣v′∣8vmin⁡3|\hat u - u(s^*)| \le \frac18 h^2 v_{\max}^2 \max|u''| \le \frac{h^2 v_{\max}^2 \max|v'|}{8 v_{\min}^3}.

Proof. On [sk,sk+1][s_k, s_{k+1}], the inverse function satisfies u(sk)=uku(s_k) = u_k and u(sk+1)=uk+hu(s_{k+1}) = u_k + h. Line L10 is the linear interpolant of uu through these two points. The error of linear interpolation of a C2C^2 function on an interval of length Δ\Delta is at most 18Δ2max⁡∣u′′∣\frac18\Delta^2\max|u''|. Here Δ=sk+1−sk≤h vmax⁡\Delta = s_{k+1} - s_k \le h\,v_{\max}, and ∣u′′∣=∣v′∣/v3≤max⁡∣v′∣/vmin⁡3|u''| = |v'|/v^3 \le \max|v'|/v_{\min}^3. □\square

So the error is O(h2)O(h^2). If vv is constant, u′′=0u'' = 0 and line L10 is exact.

Newton refinement

Lemma 3. Let g(u)=s(u)−s∗g(u) = s(u) - s^* and e=u−u(s∗)e = u - u(s^*) for the current value uu in [uk,uk+1][u_k, u_{k+1}]. One Newton step u←u−g(u)/v(u)u \leftarrow u - g(u)/v(u) gives a new error e′e' with ∣e′∣≤max⁡∣v′∣2vmin⁡e2|e'| \le \frac{\max|v'|}{2v_{\min}}e^2.

Proof. Write u∘=u(s∗)u^\circ = u(s^*). By Taylor's theorem, 0=g(u∘)=g(u)−v(u) e+12v′(ξ) e20 = g(u^\circ) = g(u) - v(u)\,e + \frac12 v'(\xi)\,e^2 for some ξ\xi between uu and u∘u^\circ. So u−g(u)/v(u)−u∘=e−g(u)/v(u)=v′(ξ)2v(u)e2u - g(u)/v(u) - u^\circ = e - g(u)/v(u) = \frac{v'(\xi)}{2v(u)}e^2. □\square

Clamping uu to [uk,uk+1][u_k, u_{k+1}] does not increase the error, because u∘u^\circ is in this interval. With the start error O(h2)O(h^2) of Lemma 2, one step gives O(h4)O(h^4) and two steps O(h8)O(h^8).

The quadrature error

Lemma 4. If each call of AGL on the interval kk returns its integral with the error δk\delta_k, then ∣sk−s(uk)∣≤η=∑j∣δj∣|s_k - s(u_k)| \le \eta = \sum_j|\delta_j| for every kk. If 2η<h vmin⁡2\eta < h\,v_{\min}, the value of lines L9 and L10 differs from the value with the exact table by at most η/(vmin⁡−2η/h)\eta/(v_{\min} - 2\eta/h).

Proof. The first claim is the triangle inequality on the sum of line L4. Let FF and F~\tilde F be the piecewise linear functions of uu through the exact and the computed table values. Lines L9 and L10 solve F~(u)=s∗\tilde F(u) = s^*, and the exact table gives the root of F(u)=s∗F(u) = s^*. On each interval, F~−F\tilde F - F is a convex combination of two end differences, so ∣F~−F∣≤η|\tilde F - F| \le \eta. The slope of F~\tilde F on an interval is at least (h vmin⁡−2η)/h>0(h\,v_{\min} - 2\eta)/h > 0. A function with this slope that is within η\eta of FF reaches s∗s^* within η\eta divided by the slope of the root of FF. □\square

The five-point Gauss-Legendre rule on an interval of length ℓ\ell has the error (5!)411 (10!)3 ℓ11f(10)(ξ)\frac{(5!)^4}{11\,(10!)^3}\,\ell^{11} f^{(10)}(\xi) for a C10C^{10} integrand, so for a smooth curve δk\delta_k 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 δk\delta_k.

Complexity

The build step calls AGL mm times. For a smooth curve and a fixed tolerance, the recursion stops after a bounded number of splits, so the build costs Θ(m)\Theta(m) 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 Θ(m)\Theta(m) space. A query costs O(log⁡m)O(\log m) for the binary search and O(1)O(1) for each Newton step, five speed evaluations for G5G_5 and one for ∣c′(u)∣|c'(u)|. If the queries come in increasing order of s∗s^*, as in an animation that moves forward, a pointer that walks through the table replaces the binary search, at O(1)O(1) amortized cost per query.

Properties

  • Second order in the spacing. The inverse by linear interpolation has the error O(h2)O(h^2); doubling mm 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, ss is linear in uu and line L10 is exact.
  • Monotone queries. Without Newton steps, the returned uu is a monotone function of s∗s^*, so the point never moves backwards.
  • A speed that jumps. The piecewise linear inverse has a derivative that jumps at the table entries, by O(h)O(h), 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 uu by Newton iteration on s(u)−s∗s(u) - s^*, with adaptive quadrature for each value of s(u)s(u). The table then only gives the start value and the length up to uku_k.
  • 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 O(n−2)O(n^{-2}) for nn chords, much worse than Gauss-Legendre quadrature.
  • Higher-order inverse. Interpolate u(s)u(s) with a cubic Hermite segment, using u′(s)=1/∣c′(u)∣u'(s) = 1/|c'(u)| at the table entries. The error is then O(h4)O(h^4) 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, ∣c′(u)∣=0|c'(u)| = 0, the inverse function is not differentiable, and Newton's method divides by 0. Stop the iteration there, or keep uu 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 10−1410^{-14} 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 s∗s^* grows linearly with time. Easing and pauses come from the curve that gives s∗s^*.

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.

arc_length_table.pyI0RawGitHub
# 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

  1. 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)
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.build
  • a full proof of time.query
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • at least three sources
  • a scene preset for the example