Algorithm Search⌘K

Techniquecore

Chebyshev spacing of precision points

Also called Chebyshev precision points.

Places the precision points of function generation at the mapped zeros of a Chebyshev polynomial, which minimizes the node factor of the structural error bound but not the error itself.

Chebyshev spacing is the rule that places the nn precision points of a function generation design at the zeros of the Chebyshev polynomial TnT_n, mapped from [−1,1][-1, 1] to the interval of the input variable. For [a,b][a, b] these points are xj=a+b2−b−a2cos⁡(2j−1)π2nx_j = \frac{a + b}{2} - \frac{b - a}{2}\cos\frac{(2j - 1)\pi}{2n}, j=1,…,nj = 1, \ldots, n, the Chebyshev nodes of the interval. The rule comes from the error of polynomial interpolation: the structural error of a linkage that is exact at the points is a product of a derivative term and the node polynomial ∏j(x−xj)\prod_j (x - x_j), and these points make the largest value of the node polynomial as small as possible. They do not minimize the structural error of the linkage itself, because the derivative term depends on the linkage, which depends on the points.

In plain words

A linkage that generates a function is exact only at a few chosen values, the precision points. Between them it is a little wrong. Where you put the precision points changes how wrong it is.

If you space them evenly, the error is usually largest near the two ends of the range. Chebyshev spacing pushes the points toward the ends, so the ends get more help. The points are the shadows on a diameter of points spread evenly around a half circle.

This rule comes from a fact about polynomials, and it is a good first choice. It does not give the best linkage. The best linkage for the largest error usually has its points somewhere else, and an optimizer can find it.

When it applies

  • A function generator, path generator or other single-input design is exact at nn precision points of one variable xx on an interval [a,b][a, b], and the goal is a small largest error over the interval.
  • The structural error e(x)e(x) is smooth (at least nn times differentiable) on [a,b][a, b], which holds when the linkage stays on one branch away from its toggle positions.
  • The number of precision points is fixed by the design method: three for Freudenstein's equation with fixed ranges, up to five with free start angles.

It is a rule for choosing data, not a solver. It does not apply to motion generation, where positions are given by the task and not chosen.

The template

The input is the function ff on [x0,x1][x_0, x_1], the angle ranges, and the number nn of precision points.

  1. CHEBYSHEV-DESIGN(f, [x0, x1], φ0, Δφ, ψ0, Δψ, n)
  2. 1for j ← 1 to n
  3. 2tj ← cos((2j − 1)π/(2n))
  4. 3xj ← (x0 + x1)/2 − ((x1 − x0)/2)·tj
  5. 4φj ← φ0 + Δφ·(xj − x0)/(x1 − x0); ψj ← ψ0 + Δψ·(f(xj) − f(x0))/(f(x1) − f(x0))
  6. 5solve the n precision point equations for the dimensions (Freudenstein's equation when n = 3)
  7. 6if there is no solution, or the precision points are not on one branch, then change the ranges and repeat
  8. 7e ← max |ψ(φ(x)) − ψd(x)| on a fine grid of x along that branch
  9. 8return the dimensions and e

Lines L1 to L3 are the spacing itself: L2 is the jj-th zero of TnT_n on [−1,1][-1, 1] and L3 maps it to [x0,x1][x_0, x_1]. The minus sign in L3 makes the points increase with jj; the set is the same with a plus sign because the zeros are symmetric about 0. Line L4 scales the points to angles, as defined on the function generation page. Line L5 is the synthesis method, for example the 3×33 \times 3 linear system of Freudenstein's equation. Lines L6 and L7 are the checks that every precision point design needs: the linkage must pass the points on one branch, and the error between the points must be measured, not assumed.

Derivation of the points

The Chebyshev polynomial is Tn(t)=cos⁡(narccos⁡t)T_n(t) = \cos(n \arccos t) on [−1,1][-1, 1], a polynomial of degree nn with leading coefficient 2n−12^{n-1} for n≥1n \ge 1 (see Chebyshev polynomials). Put t=cos⁡θt = \cos\theta with 0≤θ≤π0 \le \theta \le \pi. Then Tn(t)=0T_n(t) = 0 when cos⁡(nθ)=0\cos(n\theta) = 0, that is nθ=(2j−1)π/2n\theta = (2j - 1)\pi/2, so

θj=(2j−1)π2n,tj=cos⁡θj,j=1,…,n.\theta_j = \frac{(2j - 1)\pi}{2n}, \qquad t_j = \cos\theta_j, \qquad j = 1, \ldots, n.

These are nn distinct values in (−1,1)(-1, 1) because the θj\theta_j are distinct in (0,π)(0, \pi) and cosine is one to one there, so they are all the zeros of TnT_n. The affine map x=a+b2+b−a2tx = \frac{a + b}{2} + \frac{b - a}{2}t takes [−1,1][-1, 1] to [a,b][a, b]. Since tn+1−j=−tjt_{n+1-j} = -t_j, the images of the tjt_j are the points xj=a+b2−b−a2tjx_j = \frac{a + b}{2} - \frac{b - a}{2}t_j of line L3. The θj\theta_j are equally spaced on the half circle, and the xjx_j are their projections on the diameter, which is the picture in plain words.

The node polynomial is smallest

Let w(x)=∏j=1n(x−xj)w(x) = \prod_{j=1}^{n}(x - x_j) for any nn points xjx_j in [a,b][a, b].

Claim. For the Chebyshev points, max⁡[a,b]∣w∣=(b−a)n/22n−1\max_{[a, b]} |w| = (b - a)^n / 2^{2n - 1}, and every other choice of nn points gives a larger maximum.

Proof. Write x=a+b2+htx = \frac{a + b}{2} + h t with h=b−a2h = \frac{b - a}{2}, and xj=a+b2+hsjx_j = \frac{a + b}{2} + h s_j. Then x−xj=h(t−sj)x - x_j = h(t - s_j), so w(x)=hnq(t)w(x) = h^n q(t) with q(t)=∏j(t−sj)q(t) = \prod_j (t - s_j), a monic polynomial of degree nn in tt. The minimax property of the monic Chebyshev polynomial, proved on the Chebyshev polynomials page, says that max⁡[−1,1]∣q∣≥21−n\max_{[-1, 1]} |q| \ge 2^{1-n}, with equality only for q=21−nTnq = 2^{1-n}T_n. The proof there is short: if max⁡∣q∣≤21−n\max|q| \le 2^{1-n}, then r=21−nTn−qr = 2^{1-n}T_n - q has degree at most n−1n - 1 and (−1)kr(cos⁡(kπ/n))≥0(-1)^k r(\cos(k\pi/n)) \ge 0 at the n+1n + 1 extrema of TnT_n, which forces nn zeros counted with multiplicity, so r=0r = 0. The polynomial 21−nTn2^{1-n}T_n is monic with roots tjt_j, so it is qq exactly for the Chebyshev points. Then

max⁡[a,b]∣w∣=hn⋅21−n=(b−a)n2n⋅12n−1=(b−a)n22n−1,\max_{[a, b]}|w| = h^n \cdot 2^{1-n} = \frac{(b - a)^n}{2^n} \cdot \frac{1}{2^{n-1}} = \frac{(b - a)^n}{2^{2n - 1}},

and any other points give hnmax⁡∣q∣>hn21−nh^n \max|q| > h^n 2^{1-n}. ■\blacksquare

What this says about the linkage

Let e(x)e(x) be the structural error of a design that is exact at x1,…,xnx_1, \ldots, x_n, and suppose ee has nn continuous derivatives on [a,b][a, b]. Fix xx that is not a precision point, and let F(s)=e(s)−e(x) w(s)/w(x)F(s) = e(s) - e(x)\,w(s)/w(x). Then FF vanishes at x1,…,xnx_1, \ldots, x_n and at xx, which is n+1n + 1 points, so by Rolle's theorem applied nn times F(n)(ξ)=0F^{(n)}(\xi) = 0 for some ξ\xi in [a,b][a, b]. Since w(n)=n!w^{(n)} = n!, this gives

e(x)=e(n)(ξ)n! w(x),somax⁡[a,b]∣e∣≤max⁡[a,b]∣e(n)∣n! max⁡[a,b]∣w∣.e(x) = \frac{e^{(n)}(\xi)}{n!}\,w(x), \qquad\text{so}\qquad \max_{[a, b]}|e| \le \frac{\max_{[a, b]}|e^{(n)}|}{n!}\,\max_{[a, b]}|w|.

This is the argument of the polynomial interpolation error theorem, and it holds for any smooth ee with these zeros. For a polynomial interpolant, e(n)=f(n)e^{(n)} = f^{(n)} does not depend on the nodes, so Chebyshev points minimize the bound outright. For a linkage, e=ψ(φ(x))−ψd(x)e = \psi(\varphi(x)) - \psi_d(x) and ψ\psi is the output of a linkage whose dimensions were computed from the points. Moving the points changes the linkage and so changes e(n)e^{(n)}. Chebyshev spacing minimizes only the second factor of the bound.

So the honest statement is: Chebyshev spacing reduces the node factor of the structural error bound to its least value (b−a)n/22n−1(b - a)^n/2^{2n-1}. It does not minimize the largest structural error, and the linkage it gives is not the minimax linkage. The minimax design is characterized by an equioscillation of the error, and it is found by an exchange or by optimization, not by a formula.

Cost

The points cost O(n)O(n) cosines. The design cost is that of the synthesis method in line L5, and the check in line L7 costs one position analysis per grid point.

Classic examples

The three-point formula. For n=3n = 3, cos⁡(π/6)=3/2\cos(\pi/6) = \sqrt 3/2, so on [a,b][a, b] the points are

x1,3=a+b2∓34(b−a),x2=a+b2.x_{1,3} = \frac{a + b}{2} \mp \frac{\sqrt 3}{4}(b - a), \qquad x_2 = \frac{a + b}{2}.

On [0,1][0, 1] they are 0.066990.06699, 0.50.5, 0.933010.93301. The node polynomial has maximum 1/32=0.031251/32 = 0.03125 there, against 0.093750.09375 for the equally spaced interior points 0.25,0.5,0.750.25, 0.5, 0.75 (reached at the ends) and 3/36≈0.04811\sqrt 3/36 \approx 0.04811 for the points 0,0.5,10, 0.5, 1.

An exponential generator with Freudenstein's equation. Let f(x)=exf(x) = e^x on [0,1][0, 1], with φ\varphi from 90°90° to 210°210° and ψ\psi from 195°195° to 255°255°, and d=1d = 1. The Chebyshev points give the angle pairs (98.04°,197.42°)(98.04°, 197.42°), (150°,217.65°)(150°, 217.65°), (201.96°,248.85°)(201.96°, 248.85°). Freudenstein's equation gives K=(0.61666,0.61013,0.34006)K = (0.61666, 0.61013, 0.34006), so a=1.6216a = 1.6216, b=2.1233b = 2.1233, c=1.6390c = 1.6390. The tests of this page measure the structural error at 1000 equally spaced values of xx along the branch through the three points:

precision points max ∣e∣\lvert e\rvert where max⁡∣w∣\max \lvert w\rvert
Chebyshev 0.06700.0670, 0.50.5, 0.93300.9330 0.165°0.165° x=0x = 0 0.031250.03125
equal 0.250.25, 0.50.5, 0.750.75 0.521°0.521° x=0x = 0 0.093750.09375
ends and middle 00, 0.50.5, 11 0.200°0.200° x=0.179x = 0.179 0.048110.04811
found by a pattern search: 0.0480.048, 0.37730.3773, 11 0.104°0.104° three peaks 0.065420.06542

Chebyshev spacing cuts the error of equal spacing by a factor of about 3.2 here. The last row shows that it is not the best choice of three points: a simple search over the points, with the same ranges, finds a design whose error peaks −0.104°-0.104°, +0.104°+0.104°, −0.104°-0.104° at x=0x = 0, 0.1830.183 and 0.5970.597 are equal in size. That design has twice the node factor of the Chebyshev design and a smaller error, because its derivative factor is smaller. The Chebyshev design has end errors −0.165°-0.165° and −0.077°-0.077° and inner peaks +0.126°+0.126°, −0.026°-0.026° and +0.022°+0.022°, far from equal. Its error also crosses zero at x=0.755x = 0.755, a fourth zero that was not prescribed.

Polynomial interpolation. For interpolation of a fixed ff by a polynomial of degree n−1n - 1, the same points do minimize the bound, because there e(n)=f(n)e^{(n)} = f^{(n)}. This is the setting of the Chebyshev nodes page, and it is where the rule comes from.

A start for a minimax exchange. The Remez algorithm for polynomial minimax approximation often starts from the Chebyshev extrema. In linkage design the Chebyshev design is likewise a start for a local search on the maximum error, as in the last row of the table.

Variations

  • Other point counts. Five points with free start angles, or more points for six-bars, use the same formula with n=5n = 5 or more.
  • Chebyshev extrema. Some texts use the nn points cos⁡(kπ/(n−1))\cos(k\pi/(n - 1)), which include the ends of the interval. With precision points at the ends, the end errors are zero, but the maximum of the node polynomial is larger.
  • Weighted or derivative conditions. If some precision points are double (a value and a slope), the node polynomial has squared factors and the Chebyshev argument no longer gives the least maximum.
  • Respacing. After a first design, move the points so that the error peaks between them become equal. This is an exchange in the spirit of the Remez algorithm. In the example above it lowers the maximum error, but no convergence proof for linkages is given in the sources cited here.
  • Slider-crank generators. The same spacing is used for a slider-crank whose output is a slide.

Pitfalls

  • Calling it optimal. Chebyshev spacing minimizes a factor of a bound. The table above has a design with a 37 percent smaller error. State the measured error, and do not call the Chebyshev design minimax.
  • No measurement between the points. The rule says nothing about the size of e(n)e^{(n)}. Always evaluate the error on a fine grid along the branch.
  • Branch and assembly. Moving the points can move the linkage across a toggle position or onto another branch. Check that all precision points are on one branch, as in line L6.
  • Bad ranges. The angle ranges change the linkage more than the spacing does. On the function generation page, changing only the output start angle changes the error by a factor of three. Search the ranges as well.
  • Interpolation intuition at the ends. With equal interior spacing the error is often largest at the ends, but with Chebyshev spacing the largest error can still be at an end, as here at x=0x = 0.

Code

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.

chebyshev_spacing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chebyshev-spacing/. The authors are listed in prov/PFRWQN.jsonl.

"""Chebyshev spacing of precision points for four-bar function generation.

chebyshev_points(a, b, n) returns the zeros of the Chebyshev polynomial T_n
mapped from [-1, 1] to [a, b]:

    x_j = (a + b)/2 - ((b - a)/2) cos((2j - 1) pi / (2n)),  j = 1, ..., n.

The rest of the module builds a three-point four-bar function generator from
any three precision points and measures its structural error, so that the
spacing can be compared with others. Four-bar notation (Norton): ground d from
O2 = (0, 0) to O4 = (d, 0), input a, coupler b, output c; phi = theta2 and
psi = theta4, counterclockwise from the ground line. Freudenstein's equation
is K1 cos(psi) - K2 cos(phi) + K3 = cos(phi - psi) with K1 = d/a, K2 = d/c and
K3 = (a^2 - b^2 + c^2 + d^2) / (2ac).
"""

import math


def chebyshev_points(a, b, n):
    """The n Chebyshev points of [a, b], in increasing order."""
    if n < 1 or not a < b:
        raise ValueError("need n >= 1 and a < b")
    mid, half = (a + b) / 2.0, (b - a) / 2.0
    return [mid - half * math.cos((2 * j - 1) * math.pi / (2 * n)) for j in range(1, n + 1)]


def equal_points(a, b, n):
    """n equally spaced interior points a + (b - a) j / (n + 1)."""
    return [a + (b - a) * j / (n + 1) for j in range(1, n + 1)]


def node_polynomial(points, x):
    """w(x) = (x - x_1)(x - x_2)...(x - x_n)."""
    w = 1.0
    for p in points:
        w *= x - p
    return w


def chebyshev_bound(a, b, n):
    """max |w| on [a, b] for the Chebyshev points: (b - a)^n / 2^(2n - 1)."""
    return (b - a) ** n / 2.0 ** (2 * n - 1)


def solve3(m, r):
    """Gaussian elimination with partial pivoting; None if singular."""
    a = [list(row) + [rhs] for row, rhs in zip(m, r)]
    for col in range(3):
        piv = max(range(col, 3), key=lambda i: abs(a[i][col]))
        if abs(a[piv][col]) < 1e-14:
            return None
        a[col], a[piv] = a[piv], a[col]
        for i in range(col + 1, 3):
            f = a[i][col] / a[col][col]
            for k in range(col, 4):
                a[i][k] -= f * a[col][k]
    x = [0.0] * 3
    for i in (2, 1, 0):
        x[i] = (a[i][3] - sum(a[i][k] * x[k] for k in range(i + 1, 3))) / a[i][i]
    return x


def wrap(angle):
    """Reduce an angle to (-pi, pi]."""
    return math.pi - (math.pi - angle) % (2 * math.pi)


def output_angle(k, phi, branch):
    """psi for input phi on branch +1 or -1, from the half-angle quadratic; None if no assembly."""
    k1, k2, k3 = k
    qa = math.cos(phi) - k1 - k2 * math.cos(phi) + k3
    qb = -2.0 * math.sin(phi)
    qc = k1 - (k2 + 1.0) * math.cos(phi) + k3
    disc = qb * qb - 4.0 * qa * qc
    if disc < 0.0:
        return None
    return 2.0 * math.atan2(-qb + branch * math.sqrt(disc), 2.0 * qa)


class Generator:
    """A function generation task: f on [x0, x1] scaled to angle ranges."""

    def __init__(self, f, x0, x1, phi0, dphi, psi0, dpsi):
        self.f, self.x0, self.x1 = f, x0, x1
        self.phi0, self.dphi, self.psi0, self.dpsi = phi0, dphi, psi0, dpsi
        self.y0, self.y1 = f(x0), f(x1)

    def phi(self, x):
        return self.phi0 + (x - self.x0) / (self.x1 - self.x0) * self.dphi

    def psi(self, x):
        return self.psi0 + (self.f(x) - self.y0) / (self.y1 - self.y0) * self.dpsi

    def design(self, xs):
        """Freudenstein constants K for three precision points xs, or None."""
        if len(xs) != 3:
            raise ValueError("three precision points")
        pairs = [(self.phi(x), self.psi(x)) for x in xs]
        m = [[math.cos(ps), -math.cos(ph), 1.0] for ph, ps in pairs]
        r = [math.cos(ph - ps) for ph, ps in pairs]
        return solve3(m, r)

    def branch(self, k, xs):
        """The branch sign that passes every precision point, or None."""
        for s in (1, -1):
            ok = True
            for x in xs:
                v = output_angle(k, self.phi(x), s)
                if v is None or abs(wrap(v - self.psi(x))) > 1e-9:
                    ok = False
                    break
            if ok:
                return s
        return None

    def errors(self, k, branch, samples=1000):
        """Structural error psi(phi(x)) - psi_d(x) at equally spaced x; None if it does not assemble."""
        out = []
        for i in range(samples):
            x = self.x0 + (self.x1 - self.x0) * i / (samples - 1)
            v = output_angle(k, self.phi(x), branch)
            if v is None:
                return None
            out.append((x, wrap(v - self.psi(x))))
        return out

    def max_error(self, xs, samples=1000):
        """Largest |structural error| of the three-point design on xs, or None if it fails."""
        k = self.design(xs)
        if k is None:
            return None
        s = self.branch(k, xs)
        if s is None:
            return None
        e = self.errors(k, s, samples)
        if e is None:
            return None
        return max(abs(v) for _, v in e)


def chebyshev_design(gen, n=3, samples=1000):
    """CHEBYSHEV-DESIGN: (points, K, lengths, max error) for gen, or None if the design fails.

    With Freudenstein's equation the precision point system of line L5 is the
    3 x 3 linear system, so n must be 3 here. Line L6 reports failure; the
    caller changes the ranges and calls again.
    """
    if n != 3:
        raise ValueError("Freudenstein's equation takes three precision points")
    xs, pairs = [], []
    for j in range(1, n + 1):  # @line L1
        t = math.cos((2 * j - 1) * math.pi / (2 * n))  # @line L2
        x = (gen.x0 + gen.x1) / 2.0 - (gen.x1 - gen.x0) / 2.0 * t  # @line L3
        xs.append(x)
        pairs.append((gen.phi(x), gen.psi(x)))  # @line L4
    m = [[math.cos(ps), -math.cos(ph), 1.0] for ph, ps in pairs]
    k = solve3(m, [math.cos(ph - ps) for ph, ps in pairs])  # @line L5
    branch = gen.branch(k, xs) if k is not None else None
    if k is None or branch is None or link_lengths(k) is None:  # @line L6
        return None
    errs = gen.errors(k, branch, samples)
    if errs is None:
        return None
    e = max(abs(v) for _, v in errs)  # @line L7
    return xs, k, link_lengths(k), e  # @line L8


def link_lengths(k, d=1.0):
    """(a, b, c, d) from K; None if a coupler length is not real."""
    k1, k2, k3 = k
    if k1 == 0.0 or k2 == 0.0:
        return None
    a, c = d / k1, d / k2
    b2 = a * a + c * c + d * d - 2.0 * a * c * k3
    if b2 <= 0.0:
        return None
    return a, math.sqrt(b2), c, d
test_chebyshev_spacing.py 248 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chebyshev-spacing/. The authors are listed in prov/PFRWQN.jsonl.

import cmath
import math
import random
import unittest

from chebyshev_spacing import (
    Generator,
    chebyshev_bound,
    chebyshev_design,
    chebyshev_points,
    equal_points,
    link_lengths,
    node_polynomial,
    output_angle,
    solve3,
    wrap,
)


def cheb_t(n, t):
    """Oracle: T_n(t) by the three-term recurrence T_{k+1} = 2t T_k - T_{k-1}."""
    if n == 0:
        return 1.0
    prev, cur = 1.0, t
    for _ in range(n - 1):
        prev, cur = cur, 2.0 * t * cur - prev
    return cur


def roots_by_bisection(n, grid=20000):
    """Oracle: the zeros of T_n on [-1, 1], found by sign changes and bisection."""
    out = []
    ts = [-1.0 + 2.0 * i / grid for i in range(grid + 1)]
    for lo, hi in zip(ts, ts[1:]):
        flo, fhi = cheb_t(n, lo), cheb_t(n, hi)
        if flo == 0.0:
            out.append(lo)
            continue
        if flo * fhi < 0.0:
            for _ in range(80):
                mid = (lo + hi) / 2.0
                if cheb_t(n, lo) * cheb_t(n, mid) <= 0.0:
                    hi = mid
                else:
                    lo = mid
            out.append((lo + hi) / 2.0)
    return out


def output_by_circles(a, b, c, d, phi, near):
    """Oracle: psi from the intersection of circle(A, b) and circle(O4, c), the point nearest to `near`."""
    pa = a * cmath.exp(1j * phi)
    o4 = complex(d, 0.0)
    dist = abs(o4 - pa)
    x = (b * b - c * c + dist * dist) / (2.0 * dist)
    h2 = b * b - x * x
    if h2 < 0.0:
        return None
    e = (o4 - pa) / dist
    cands = [pa + e * complex(x, s * math.sqrt(h2)) for s in (1.0, -1.0)]
    psis = [cmath.phase(p - o4) for p in cands]
    return min(psis, key=lambda v: abs(wrap(v - near)))


class TestPoints(unittest.TestCase):
    def test_zeros_of_t_n(self):
        for n in range(1, 13):
            xs = chebyshev_points(-1.0, 1.0, n)
            for x in xs:
                self.assertLess(abs(cheb_t(n, x)), 1e-12)
            oracle = roots_by_bisection(n)
            self.assertEqual(len(oracle), n)
            for x, y in zip(xs, oracle):
                self.assertAlmostEqual(x, y, delta=1e-12)

    def test_mapping_is_affine(self):
        rng = random.Random(11)
        for _ in range(200):
            a = rng.uniform(-5, 5)
            b = a + rng.uniform(0.1, 10)
            n = rng.randint(1, 9)
            xs = chebyshev_points(a, b, n)
            ts = chebyshev_points(-1.0, 1.0, n)
            self.assertEqual(xs, sorted(xs))
            for x, t in zip(xs, ts):
                self.assertAlmostEqual(x, (a + b) / 2 + (b - a) / 2 * t, delta=1e-12 * (1 + abs(a) + abs(b)))
                self.assertTrue(a < x < b)
            for x, y in zip(xs, reversed(xs)):
                self.assertAlmostEqual(x + y, a + b, delta=1e-12 * (1 + abs(a) + abs(b)))

    def test_three_points_on_unit_interval(self):
        xs = chebyshev_points(0.0, 1.0, 3)
        r = math.sqrt(3) / 4
        for x, y in zip(xs, [0.5 - r, 0.5, 0.5 + r]):
            self.assertAlmostEqual(x, y, delta=1e-15)
        self.assertEqual(equal_points(0.0, 1.0, 3), [0.25, 0.5, 0.75])

    def test_bad_input(self):
        with self.assertRaises(ValueError):
            chebyshev_points(0.0, 1.0, 0)
        with self.assertRaises(ValueError):
            chebyshev_points(1.0, 1.0, 3)


class TestNodePolynomial(unittest.TestCase):
    def extremal_points(self, a, b, n):
        return [(a + b) / 2 + (b - a) / 2 * math.cos(k * math.pi / n) for k in range(n + 1)]

    def test_equioscillation_of_chebyshev_nodes(self):
        for n in range(1, 11):
            a, b = -0.5, 2.5
            xs = chebyshev_points(a, b, n)
            bound = chebyshev_bound(a, b, n)
            ext = self.extremal_points(a, b, n)
            for k, x in enumerate(ext):
                w = node_polynomial(xs, x)
                self.assertAlmostEqual(abs(w), bound, delta=1e-12 * bound)
                if k > 0:
                    prev = node_polynomial(xs, ext[k - 1])
                    self.assertLess(w * prev, 0.0)
            grid = max(abs(node_polynomial(xs, a + (b - a) * i / 4000)) for i in range(4001))
            self.assertLessEqual(grid, bound * (1 + 1e-12))

    def test_no_node_set_does_better(self):
        # For any n nodes, max |w| over the n + 1 extremal points is already at least the bound.
        rng = random.Random(2024)
        for _ in range(3000):
            n = rng.randint(1, 8)
            a = rng.uniform(-3, 3)
            b = a + rng.uniform(0.5, 4)
            nodes = sorted(rng.uniform(a, b) for _ in range(n))
            bound = chebyshev_bound(a, b, n)
            peak = max(abs(node_polynomial(nodes, x)) for x in self.extremal_points(a, b, n))
            self.assertGreaterEqual(peak, bound * (1 - 1e-12))

    def test_equal_spacing_is_worse(self):
        for n in range(2, 12):
            eq = equal_points(0.0, 1.0, n)
            peak = max(abs(node_polynomial(eq, i / 20000)) for i in range(20001))
            self.assertGreater(peak, chebyshev_bound(0.0, 1.0, n))


class TestFunctionGenerator(unittest.TestCase):
    def setUp(self):
        d = math.radians
        # y = e^x on [0, 1]; phi from 90 to 210 degrees; psi from 195 to 255 degrees.
        self.g = Generator(math.exp, 0.0, 1.0, d(90), d(120), d(195), d(60))

    def check_design(self, xs):
        g = self.g
        k = g.design(xs)
        self.assertIsNotNone(k)
        a, b, c, d = link_lengths(k)
        s = g.branch(k, xs)
        self.assertIsNotNone(s)
        for x in xs:
            phi, psi = g.phi(x), g.psi(x)
            self.assertLess(abs(wrap(output_angle(k, phi, s) - psi)), 1e-12)
            pa = a * cmath.exp(1j * phi)
            pb = d + c * cmath.exp(1j * psi)
            self.assertAlmostEqual(abs(pb - pa), b, delta=1e-12)
            self.assertAlmostEqual(k[0] * math.cos(psi) - k[1] * math.cos(phi) + k[2], math.cos(phi - psi), delta=1e-12)
        return k, (a, b, c, d), s

    def test_precision_points_are_met(self):
        for xs in (chebyshev_points(0.0, 1.0, 3), equal_points(0.0, 1.0, 3), [0.0, 0.5, 1.0]):
            self.check_design(xs)

    def test_half_angle_matches_circle_intersection(self):
        k, (a, b, c, d), s = self.check_design(chebyshev_points(0.0, 1.0, 3))
        errs = self.g.errors(k, s, 1000)
        self.assertIsNotNone(errs)
        for x, _ in errs[::7]:
            phi = self.g.phi(x)
            psi = output_angle(k, phi, s)
            other = output_by_circles(a, b, c, d, phi, psi)
            self.assertLess(abs(wrap(psi - other)), 1e-9)

    def test_structural_error_at_1000_points(self):
        g = self.g
        ec = g.max_error(chebyshev_points(0.0, 1.0, 3), 1000)
        ee = g.max_error(equal_points(0.0, 1.0, 3), 1000)
        self.assertAlmostEqual(math.degrees(ec), 0.1649, delta=5e-4)
        self.assertAlmostEqual(math.degrees(ee), 0.5210, delta=5e-4)
        self.assertLess(ec, ee)

    def test_not_minimax(self):
        # Three other precision points give a smaller largest error, so the spacing is not minimax.
        g = self.g
        ec = g.max_error(chebyshev_points(0.0, 1.0, 3), 1000)
        better = g.max_error([0.048, 0.3773, 0.9999], 1000)
        self.assertIsNotNone(better)
        self.assertLess(better, 0.7 * ec)
        # The Chebyshev error peaks are unequal: no equioscillation.
        k = g.design(chebyshev_points(0.0, 1.0, 3))
        errs = [v for _, v in g.errors(k, g.branch(k, chebyshev_points(0.0, 1.0, 3)), 1000)]
        self.assertGreater(abs(errs[0]), 2 * abs(errs[-1]))

    def test_template_matches_parts(self):
        out = chebyshev_design(self.g, 3, 1000)
        self.assertIsNotNone(out)
        xs, k, lengths, e = out
        self.assertEqual(xs, chebyshev_points(0.0, 1.0, 3))
        self.assertEqual(k, self.g.design(xs))
        self.assertEqual(e, self.g.max_error(xs, 1000))
        for got, want in zip(lengths, (1.6216, 2.1233, 1.6390, 1.0)):
            self.assertAlmostEqual(got, want, delta=5e-5)
        with self.assertRaises(ValueError):
            chebyshev_design(self.g, 4)

    def test_template_reports_failure(self):
        # Ranges for which the three pairs are not on one branch or do not assemble.
        rng = random.Random(7)
        failures = 0
        for _ in range(200):
            g = Generator(math.exp, 0.0, 1.0, rng.uniform(0, 6.3), rng.uniform(0.5, 2.5), rng.uniform(0, 6.3), rng.uniform(0.5, 2.5))
            out = chebyshev_design(g, 3, 200)
            if out is None:
                failures += 1
                continue
            xs, k, lengths, e = out
            s = g.branch(k, xs)
            for x in xs:
                self.assertLess(abs(wrap(output_angle(k, g.phi(x), s) - g.psi(x))), 1e-9)
        self.assertGreater(failures, 0)

    def test_singular_system(self):
        self.assertIsNone(self.g.design([0.3, 0.3, 0.7]))
        self.assertIsNone(solve3([[1, 2, 3], [2, 4, 6], [0, 1, 1]], [1, 2, 3]))

    def test_solver_against_known_solution(self):
        rng = random.Random(5)
        for _ in range(500):
            m = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(3)]
            x = [rng.uniform(-2, 2) for _ in range(3)]
            r = [sum(m[i][j] * x[j] for j in range(3)) for i in range(3)]
            y = solve3(m, r)
            if y is None:
                continue
            res = max(abs(sum(m[i][j] * y[j] for j in range(3)) - r[i]) for i in range(3))
            self.assertLess(res, 1e-10)


if __name__ == "__main__":
    unittest.main()

Exercises

  1. Derive the five-point formula on [0,1][0, 1] and compute max⁡∣w∣\max|w| for it and for the points 1/6,2/6,…,5/61/6, 2/6, \ldots, 5/6.
  2. Prove that the extrema of ww for the Chebyshev points are at x=a+b2+b−a2cos⁡(kπ/n)x = \frac{a + b}{2} + \frac{b - a}{2}\cos(k\pi/n), k=0,…,nk = 0, \ldots, n, and that the signs alternate.
  3. For the exponential example, change Δψ\Delta\psi to 90°90°, repeat the design with Chebyshev and equal spacing, and compare the measured errors.
  4. The pattern search design in the table has a larger node factor than the Chebyshev design and a smaller error. Use the error formula e(x)=e(3)(ξ)w(x)/3!e(x) = e^{(3)}(\xi)w(x)/3! to explain how both can hold.
  5. Implement the respacing exchange: move the points until the error peaks between and outside them are equal in size, and compare with the pattern search above.

References

  1. Ferdinand Freudenstein, Approximate synthesis of four-bar linkages, Transactions of the ASME 77(8), 1955, 853 to 861, precision point function generation, the structural error, and the spacing of the precision points
  2. Richard S. Hartenberg and Jacques Denavit, Kinematic Synthesis of Linkages, McGraw-Hill, New York, 1964, the chapter on precision point spacing and the structural error of function generators (general locator)
  3. John J. Uicker, Gordon R. Pennock and Joseph E. Shigley, Theory of Machines and Mechanisms, 5th edition, Oxford University Press, 2017, the chapter on the synthesis of linkages (precision positions, structural error and Chebychev spacing; chapter level only)
  4. Arthur G. Erdman, George N. Sandor and Sridhar Kota, Mechanism Design, Analysis and Synthesis, Volume 1, 4th edition, Prentice Hall, 2001, Chapter 8, Introduction to Kinematic Synthesis (function generation and the choice of precision points)
  5. Theodore J. Rivlin, Chebyshev Polynomials, second edition, Wiley, 1990, Chapter 1 (zeros and extrema of T_n) and Chapter 2 (extremal properties, the monic polynomial of least deviation)

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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
  • three classic examples