Algorithmcore
Jury stability test
Also called Jury test, Jury criterion.
Decides from a table built on the coefficients whether every root of a real polynomial lies inside the unit circle, and counts the roots outside. O(n^2) operations.
- Time
- O(n^2) worst
- Space
- O(n) extra
- Where
- n = the degree of the polynomial
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Eliahu I. Jury, J. Blanchard, 1961
The Jury stability test decides whether every root of a real polynomial lies inside the open unit circle, that is, whether is Schur. It never computes a root. It builds a table from the coefficients: each pass removes the constant term of the current polynomial with a multiple of its reversed copy, which lowers the degree by one, and the leading coefficients of the polynomials form the first column of the table. If is the characteristic polynomial of a discrete-time linear system , or the denominator of a closed-loop transfer function in the variable of the z-transform, the test decides whether is Schur, and so whether the equilibrium is asymptotically stable. It is the discrete-time counterpart of the Routh array. The Schur-Cohn test on another page uses the same recursion for complex polynomials; this page says below how the two tables differ.
In plain words
Write the coefficients of the polynomial in a row, and below them the same numbers in reverse order. Divide the last number of the top row by the first one. Subtract that multiple of the reversed row from the top row. The last entry becomes zero, so drop it. The new row is one shorter. Repeat with the new row and its reverse until one number is left. Read down the first entries of the rows. If all of them are positive, every root is inside the unit circle. If none of them is zero, the number of negative entries is the number of roots outside the circle. A zero entry means that the test is singular: some root is on the circle, or two roots are mirror images in the circle.
The problem
Given a real polynomial with , written with the highest power first, decide whether all its roots satisfy . When the answer is no, count the roots with , counted with multiplicity, if the table allows it.
A matrix is Schur if every eigenvalue has modulus less than , and a polynomial is Schur in the same sense for its roots. The usual source of is for the matrix of a discrete-time model, for example the zero-order hold model of a continuous plant with sampling period , or the closed-loop characteristic polynomial of a sampled-data system.
Notation. is the polynomial of degree in the table, with coefficients (highest power first). Its reversed polynomial is . The number is the reflection coefficient of step , and is the first column: the leading coefficients of .
The algorithm
JURY(a_0, ..., a_n) ▷ p(z) = a_0 z^n + ... + a_n, real- 1
remove zero leading coefficients (error if none is left); if a_0 < 0 then negate every a_i - 2
c ← (a_0, ..., a_n); F ← (a_0) - 3
for k ← n down to 1 do ▷ c holds the k + 1 coefficients of p_k - 4
α_k ← c_k / c_0 - 5
c ← (c_i - α_k · c_{k-i} for i = 0, ..., k - 1) ▷ p_{k-1}: (p_k - α_k p_k*) / z - 6
append c_0 to F - 7
if c_0 = 0 then return (F, "singular") ▷ |α_k| = 1: p is not Schur - 8
N ← the number of negative entries of F - 9
return (F, N) ▷ N roots outside the circle; p is Schur iff N = 0
Line L1 makes the leading coefficient positive, which changes no root. Line L5 subtracts times the reversed row from the row. The last entry becomes , so the result is , and the new leading coefficient is . So the first entry keeps its sign when , changes its sign when , and is zero when . Line L7 stops on a zero entry. In a printed Jury table each polynomial takes two rows, the coefficients and their reverse, so the table has rows.
The implementation computes in exact rational arithmetic and converts floating point input exactly. It returns the rows, the first column, the numbers , the count (or "singular"), and the verdict. It also has the classic conditions of Jury and Blanchard (see Variants) as a second, independent check.
Example
The check value. For :
| row | entries | |
|---|---|---|
| , , | ||
| , , | ||
| , | ||
| , | ||
The first column is positive, so is Schur. Indeed the roots are , both of modulus .
One root outside. For the rows are , then with the row , then with the row , then with the row . The first column has one negative entry, so one root lies outside the circle: the root . The double root causes no difficulty.
A gain range. Take the plant , with time in seconds, sampled with a zero-order hold at s, a delay of one sample for the computation, and the controller . The loop transfer function is with and , and the closed-loop polynomial is . For a general the table gives , the first entry , then . The first column is positive exactly when
the well known stability triangle. Here this gives . At the two closed-loop poles are on the unit circle at the angle rad. The continuous loop without the sample and the delay would be asymptotically stable for every ; the sampling and the delay create the upper limit.
Singular tables. For the first column is : a root on the circle. For it is at once, because . This polynomial has no root on the circle, but its two roots are mirror images in the circle. The cubic gives for the same reason.
Correctness
The proofs are in the correctness proof.
- One step (proved). If has no root on the circle and , then has no root on the circle. It has as many roots outside the circle as when , and minus that number when . The proof uses on the circle and Rouché's theorem.
- The count (proved). If no entry of is zero, has no root on the circle, and the number of negative entries of is the number of roots outside the circle. So is Schur exactly when every entry is positive.
- Singular tables (proved). A root on the circle, or a pair of roots and , always gives a zero entry. A Schur polynomial never gives one, so a singular table means that is not Schur. The count is not available in that case.
- The classic conditions (proved). For and , is Schur if and only if , and for .
- Termination (proved). Each pass shortens the row by one, so there are at most passes.
The tests compare the verdict and the count with the moduli of the roots from the Durand-Kerner method on more than 1000 random polynomials of degree at most 6 with integer coefficients from to , skipping those with a root within of the circle. They also check the stability triangle on a grid, exact counts for polynomials built from known rational roots, and the relation to the Schur transform below.
Proof: The Jury table decides whether a real polynomial is Schur, and in the regular case the number of negative first-column entries is the number of roots outside the unit circlefull
Let be real with (line L1 makes positive; multiplying by changes no root). The arithmetic is exact. For a real polynomial of exact degree , let be the reversed polynomial (the same coefficients in the opposite order). Write and . For with no root on , and are the numbers of roots of in and outside , counted with multiplicity, so .
The algorithm computes and, while the leading coefficient of is not zero, and
whose coefficients are , (line L5). The first column is with the leading coefficient of .
Lemma 1: one step
Let have exact degree , leading coefficient and constant term .
(a) The right side of (1) has constant term , so is a polynomial of degree at most , and its coefficient of is .
(b) has the sign of if , the opposite sign if , and if .
(c) If has no root on and , then has exact degree , no root on , and
Proof. (a) The constant term of is , so the constant term of the right side is . The leading coefficient of is , so the coefficient of on the right side is . (b) follows from (a).
(c) By (b), , so . For , , and since the coefficients are real, . So on , and this is positive because has no root on .
If , then on . So on , and by Rouché's theorem and have the same number of roots in . The factor adds the root , so , and .
If , then on , has no root on , and by Rouché's theorem has as many roots in as . The roots of are the reciprocals of the roots of (none of which is , because has degree only if , and gives ), with the same multiplicities. So . Then and .
Lemma 2: a root on the circle makes the table singular
If has a root , then some entry of is zero.
Proof. Suppose that and has exact degree . Then , and by (1), because . If no entry of were zero, every would have exact degree , and by induction . But is the nonzero constant . This is a contradiction.
The same argument shows that a pair of roots and of (a common root of and ) also makes the table singular.
Theorem
The loop runs at most times. Let the algorithm return.
(i) If no entry of is zero (the regular case), then has no root on , and the number of negative entries of equals . In particular is Schur if and only if .
(ii) If some entry of is zero (the singular case), then is not Schur.
Proof. Termination: each pass lowers the length of the coefficient list by exactly one, so there are at most passes.
(i) By Lemma 2, has no root on . Since every , Lemma 1(b) gives for every , and Lemma 1(c) applies at every step. Let be the sign of and let be the number of indices with . We show by induction on . For , is a nonzero constant, and . Let .
- If , then by Lemma 1(b), so , and by Lemma 1(c).
- If , then . Index counts in , and an index counts in exactly when . So . By Lemma 1(c), .
For , because , so is the number of negative entries of , which is .
(ii) Let be the first zero entry, so and , where is the constant term of . Suppose that is Schur. Then, by induction with Lemma 1, every with is Schur: is Schur, and if is Schur then is the product of the moduli of the roots of , which is less than , so Lemma 1(c) gives . But then , which contradicts . So is not Schur.
Corollary: the n + 1 conditions of the classic table
For and , is Schur if and only if , , and for .
Proof. By the theorem and Lemma 1(b), is Schur if and only if for (then all are positive). At , (1) gives , because . At , , so . If for , the factors are positive. Then has the sign of , and has the sign of . The polynomial has , and holds if and only if and . So, under for , the condition is equivalent to and . If some with , both sides of the claim are false.
The classic table forms the rows without the division by , so each row is a positive or negative multiple of the row above, and the test becomes , which does not depend on that factor.
Complexity
Costs are in the real-RAM model, one unit per arithmetic operation on the coefficients.
- Time. The pass for degree costs one division and multiplications and subtractions. In all this is divisions and multiplications, so operations.
- Space. numbers if only the current row and the first column are kept, and for the whole printed table.
- Exact arithmetic. With rational coefficients the entries are rational, and their numerators and denominators can grow from row to row. The operation count stays , but the cost in bit operations is higher.
- Compared with root finding. Computing all roots and their moduli also costs operations per iteration of a method such as Durand-Kerner, but it needs a tolerance. The table gives an exact answer in rational arithmetic, and it works with symbolic coefficients such as a gain .
Properties
- Exact. In rational arithmetic the verdict is a proof, not an estimate.
- Symbolic. Entries can contain a parameter, and the conditions "first column positive" become inequalities in that parameter, as in the gain example.
- Scale. Multiplying by a positive number scales every row by that number and does not change in sign.
- Reflection coefficients. is Schur if and only if for every . The numbers are the reflection coefficients of the step-down recursion that inverts the Levinson-Durbin recursion, which is how signal processing checks that an all-pole filter is stable.
Variants and improvements
- The classic table of Jury and Blanchard. It forms each new row without division, as the determinants , and stops at the row of degree 2, so the table has rows. The test is then the conditions , , , and in each later row (Ogata 1995, Chapter 4). The first two conditions are cheap necessary checks that often end the test early. The rows differ from the rows of this page only by a nonzero factor, and the conditions are equivalent (see the proof).
- Relation to the Schur-Cohn test. The Schur-Cohn test allows complex coefficients. It cancels the leading coefficient with the transform , keeps the coefficients as integers by dividing by their content, and counts the roots inside the circle. The Jury table cancels the constant term instead, divides by the leading coefficient, and reads the signs of the first column. For a real the row is in reversed order, multiplied by . So the two tables carry the same polynomials, and they become singular for the same inputs.
- The bilinear map. The substitution maps the unit disc onto the left half plane, so the Routh array of the transformed polynomial also decides the question. This is the bilinear transform without the sampling period. It costs more operations and can create a root at infinity that needs care, so the direct table is usually better.
- The Bistritz table. A later table by Bistritz works with a three-term recursion on the symmetric and antisymmetric parts of , and needs fewer multiplications.
- Margins inside the disc. To test whether all roots satisfy , run the table on . For the damping of a sampled loop, gives a decay rate per sample.
When to use it
Use the Jury table for the characteristic polynomial of a discrete-time loop of small order, for hand calculations, and when a coefficient depends on a parameter, as for the range of a gain. For a numerical matrix of high order, do not form the characteristic polynomial, because its roots can be very sensitive to the coefficients (see root conditioning). Compute the eigenvalues, or the spectral radius, of the matrix instead, or use the discrete Lyapunov theorem .
Pitfalls
- Zero entries in floating point. A first entry that is zero in exact arithmetic comes out as a tiny number of either sign in floating point, and the count can then be wrong. A tiny entry means that a root is near the circle. The implementation computes exactly to avoid this.
- Singular without a root on the circle. A zero entry does not prove a root on the circle. The polynomial has the roots and . The verdict "not Schur" is still correct, but the count needs another method, for example the table of for an slightly different from .
- A negative leading coefficient. The count "number of negative entries" assumes . Negate first.
- The two forms of the table. Some books write the coefficients with the lowest power first, and some build the rows from the last entries. The meaning of "first entry" changes with the form. Check the conditions on a known polynomial, such as , before you use a table from a book.
- Continuous-time rules. Positive coefficients are necessary for a Hurwitz polynomial, but they say nothing for the unit circle: is Schur with a negative coefficient, and is not Schur with positive coefficients.
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
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra and polynomial routines for the control pages.
Conventions:
- A matrix is a list of rows. Entries are int, float, Fraction or complex.
- A vector is a flat list of scalars. matvec, dot, solve (with a vector
right side), vec and unvec use flat lists.
- A polynomial is a list of coefficients, highest power first, so
[1, 3, 2] is s^2 + 3 s + 2.
- Routines that divide (solve, inv, det, charpoly) compute in Fraction when
every entry is an int or a Fraction, so the result is exact. With float or
complex entries they compute in floating point.
- transpose does not conjugate complex entries.
Floating point tolerances:
- expm: scaling and squaring with a Taylor series; the scaled matrix has
infinity norm at most 1/2 and the series stops when a term is below
2^-60 times the sum. For matrices that are not far from normal the relative
error is near 1e-14.
- polyroots: Durand-Kerner iteration, then a Newton polish. Simple roots of a
well conditioned polynomial come out with a relative error near 1e-12 (the
tests ask for 1e-9). A root of multiplicity k is ill conditioned: its error
grows like 1e-16^(1/k), about 1e-8 for a double root and 1e-3 for a
fourfold root. For real coefficients the output is closed under
conjugation.
- is_pos_def with float entries: the matrix must be symmetric within
1e-12 times its largest entry, and the Cholesky pivots of A - margin I must
be positive.
This file holds no algorithm of a control page.
"""
import cmath
import math
from fractions import Fraction
__all__ = [
"zeros", "eye", "add", "sub", "scale", "mul", "transpose", "matvec",
"dot", "norm2", "block", "kron", "vec", "unvec", "solve", "inv", "det",
"trace", "charpoly", "polyval", "polyadd", "polymul", "polyder",
"polyroots", "expm", "mat_power", "is_symmetric", "is_pos_def",
]
def _is_exact(v):
return isinstance(v, (int, Fraction))
def _all_exact(*mats):
for m in mats:
for row in m:
if isinstance(row, list):
for v in row:
if not _is_exact(v):
return False
elif not _is_exact(row):
return False
return True
def _to_fraction(a):
return [[Fraction(v) for v in row] for row in a]
def _shape(a):
return len(a), (len(a[0]) if a else 0)
def zeros(n, m=None):
"""Return the n by m zero matrix (n by n if m is None), with int entries."""
if m is None:
m = n
return [[0] * m for _ in range(n)]
def eye(n):
"""Return the n by n identity matrix, with int entries."""
return [[1 if i == j else 0 for j in range(n)] for i in range(n)]
def add(a, b):
"""Return a + b."""
if _shape(a) != _shape(b):
raise ValueError("add: shapes differ")
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
def sub(a, b):
"""Return a - b."""
if _shape(a) != _shape(b):
raise ValueError("sub: shapes differ")
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
def scale(c, a):
"""Return the scalar c times the matrix a."""
return [[c * x for x in row] for row in a]
def mul(a, b):
"""Return the matrix product a b."""
n, k = _shape(a)
k2, m = _shape(b)
if k != k2:
raise ValueError("mul: inner dimensions differ")
bt = list(zip(*b)) if b else []
out = []
for row in a:
out_row = []
for col in bt:
s = 0
for x, y in zip(row, col):
s += x * y
out_row.append(s)
out.append(out_row)
return out
def transpose(a):
"""Return the transpose of a (no complex conjugation)."""
return [list(col) for col in zip(*a)]
def matvec(a, x):
"""Return the vector a x, for a flat list x."""
if a and len(a[0]) != len(x):
raise ValueError("matvec: dimensions differ")
out = []
for row in a:
s = 0
for v, w in zip(row, x):
s += v * w
out.append(s)
return out
def dot(x, y):
"""Return sum of x_i y_i (no complex conjugation)."""
if len(x) != len(y):
raise ValueError("dot: lengths differ")
s = 0
for v, w in zip(x, y):
s += v * w
return s
def _sym_eigvals(s):
"""Eigenvalues of a real symmetric float matrix by cyclic Jacobi."""
n = len(s)
a = [list(map(float, row)) for row in s]
for _ in range(100):
off = sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
diag = sum(a[i][i] ** 2 for i in range(n))
if off <= 1e-30 * max(diag, 1e-300):
break
for p in range(n - 1):
for q in range(p + 1, n):
if a[p][q] == 0.0:
continue
theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
sn = t * c
for k in range(n):
akp, akq = a[k][p], a[k][q]
a[k][p] = c * akp - sn * akq
a[k][q] = sn * akp + c * akq
for k in range(n):
apk, aqk = a[p][k], a[q][k]
a[p][k] = c * apk - sn * aqk
a[q][k] = sn * apk + c * aqk
return [a[i][i] for i in range(n)]
def norm2(x):
"""Return the 2-norm.
For a flat vector this is the Euclidean norm. For a matrix it is the
induced 2-norm (the largest singular value), computed from the
eigenvalues of M^T M by the Jacobi method, where M is a real matrix with
the same singular values. The result is a float.
"""
if not x:
return 0.0
if not isinstance(x[0], list):
return math.sqrt(sum(abs(complex(v)) ** 2 for v in x))
if any(isinstance(v, complex) for row in x for v in row):
re = [[complex(v).real for v in row] for row in x]
im = [[complex(v).imag for v in row] for row in x]
m = block([[re, scale(-1, im)], [im, re]])
else:
m = [[float(v) for v in row] for row in x]
g = mul(transpose(m), m)
lam = max(_sym_eigvals(g))
return math.sqrt(max(lam, 0.0))
def block(rows):
"""Build a matrix from a list of rows of blocks.
A block is a matrix, or the int 0 for a zero block whose size is taken
from the other blocks in its block row and block column.
"""
heights = []
for r in rows:
h = None
for b in r:
if isinstance(b, list):
h = len(b)
break
if h is None:
raise ValueError("block: a block row has no matrix block")
heights.append(h)
ncols = len(rows[0])
widths = []
for j in range(ncols):
w = None
for r in rows:
if isinstance(r[j], list):
w = len(r[j][0]) if r[j] else 0
break
if w is None:
raise ValueError("block: a block column has no matrix block")
widths.append(w)
out = []
for r, h in zip(rows, heights):
if len(r) != ncols:
raise ValueError("block: block rows have different lengths")
for i in range(h):
line = []
for b, w in zip(r, widths):
if isinstance(b, list):
if len(b) != h or (b and len(b[0]) != w):
raise ValueError("block: block sizes do not match")
line.extend(b[i])
elif b == 0:
line.extend([0] * w)
else:
raise ValueError("block: a scalar block must be 0")
out.append(line)
return out
def kron(a, b):
"""Return the Kronecker product of a and b."""
n, m = _shape(a)
p, q = _shape(b)
return [[a[i // p][j // q] * b[i % p][j % q] for j in range(m * q)] for i in range(n * p)]
def vec(a):
"""Stack the columns of a into one flat list."""
n, m = _shape(a)
return [a[i][j] for j in range(m) for i in range(n)]
def unvec(v, n, m=None):
"""Inverse of vec: return the n by m matrix whose stacked columns are v."""
if m is None:
m = len(v) // n
if n * m != len(v):
raise ValueError("unvec: length does not match the shape")
return [[v[j * n + i] for j in range(m)] for i in range(n)]
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a flat vector or a matrix; the result has the same form. With int
and Fraction entries the result is exact (Fraction). Raises ValueError
if a is singular (an exactly zero pivot).
"""
n, m = _shape(a)
if n != m:
raise ValueError("solve: matrix is not square")
is_vec = not (b and isinstance(b[0], list))
rhs = [[v] for v in b] if is_vec else [list(row) for row in b]
if len(rhs) != n:
raise ValueError("solve: right side has the wrong length")
if _all_exact(a, rhs):
aa = _to_fraction(a)
rhs = _to_fraction(rhs)
else:
aa = [list(row) for row in a]
k = len(rhs[0]) if rhs else 0
for c in range(n):
p = max(range(c, n), key=lambda r: abs(aa[r][c]))
if aa[p][c] == 0:
raise ValueError("solve: matrix is singular")
if p != c:
aa[c], aa[p] = aa[p], aa[c]
rhs[c], rhs[p] = rhs[p], rhs[c]
piv = aa[c][c]
for r in range(c + 1, n):
f = aa[r][c] / piv
if f == 0:
continue
row_r, row_c = aa[r], aa[c]
for j in range(c, n):
row_r[j] -= f * row_c[j]
rr, rc = rhs[r], rhs[c]
for j in range(k):
rr[j] -= f * rc[j]
x = [[0] * k for _ in range(n)]
for c in range(n - 1, -1, -1):
for j in range(k):
s = rhs[c][j]
for t in range(c + 1, n):
s -= aa[c][t] * x[t][j]
x[c][j] = s / aa[c][c]
return [row[0] for row in x] if is_vec else x
def inv(a):
"""Return the inverse of a (exact with int and Fraction entries)."""
return solve(a, eye(len(a)))
def det(a):
"""Return the determinant of a by elimination with partial pivoting.
With int and Fraction entries the result is an exact Fraction.
"""
n, m = _shape(a)
if n != m:
raise ValueError("det: matrix is not square")
aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
d = Fraction(1) if _all_exact(a) else 1.0
for c in range(n):
p = max(range(c, n), key=lambda r: abs(aa[r][c]))
if aa[p][c] == 0:
return d * 0
if p != c:
aa[c], aa[p] = aa[p], aa[c]
d = -d
piv = aa[c][c]
d *= piv
for r in range(c + 1, n):
f = aa[r][c] / piv
if f == 0:
continue
for j in range(c, n):
aa[r][j] -= f * aa[c][j]
return d
def trace(a):
"""Return the sum of the diagonal entries of a."""
s = 0
for i in range(len(a)):
s += a[i][i]
return s
def charpoly(a):
"""Return [1, a_1, ..., a_n] with det(s I - A) = s^n + a_1 s^(n-1) + ... + a_n.
Uses the Faddeev-LeVerrier recursion M_k = A M_(k-1) + a_(k-1) I,
a_k = -trace(A M_k) / k. Exact with int and Fraction entries.
"""
n, m = _shape(a)
if n != m:
raise ValueError("charpoly: matrix is not square")
aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
coeffs = [1]
mk = zeros(n)
for k in range(1, n + 1):
mk = mul(aa, mk)
c = coeffs[-1]
for i in range(n):
mk[i][i] += c
am = mul(aa, mk)
coeffs.append(-trace(am) / k)
return coeffs
def polyval(p, x):
"""Evaluate the polynomial p at x by Horner's rule."""
s = 0
for c in p:
s = s * x + c
return s
def _strip(p):
i = 0
while i < len(p) - 1 and p[i] == 0:
i += 1
return list(p[i:]) if p else [0]
def polyadd(p, q):
"""Return p + q, with exactly zero leading coefficients removed."""
n = max(len(p), len(q))
pp = [0] * (n - len(p)) + list(p)
qq = [0] * (n - len(q)) + list(q)
return _strip([x + y for x, y in zip(pp, qq)])
def polymul(p, q):
"""Return the product p q."""
if not p or not q:
return [0]
out = [0] * (len(p) + len(q) - 1)
for i, x in enumerate(p):
for j, y in enumerate(q):
out[i + j] += x * y
return _strip(out)
def polyder(p):
"""Return the derivative of p."""
n = len(p) - 1
if n <= 0:
return [0]
return _strip([c * (n - i) for i, c in enumerate(p[:-1])])
def polyroots(p, tol=1e-15, maxiter=1000):
"""Return the complex roots of p, sorted by real part, then imaginary part.
Durand-Kerner (Weierstrass) iteration from points on a circle, stopped
when every relative correction is below tol, then a Newton polish of
each root. For real coefficients the roots are made exactly real or
exact conjugate pairs. See the module notes for the accuracy.
"""
c = [complex(v) for v in p]
while c and c[0] == 0:
c.pop(0)
if not c:
raise ValueError("polyroots: zero polynomial")
real_coeffs = all(v.imag == 0 for v in c)
origin = 0
while len(c) > 1 and c[-1] == 0:
c.pop()
origin += 1
n = len(c) - 1
a = [v / c[0] for v in c]
if n == 0:
z = []
elif n == 1:
z = [-a[1]]
else:
r = 2.0 * max(abs(a[k]) ** (1.0 / k) for k in range(1, n + 1))
if r == 0:
r = 1.0
z = [r * cmath.exp(1j * (2 * math.pi * k / n + 0.4)) for k in range(n)]
for _ in range(maxiter):
worst = 0.0
for i in range(n):
den = 1.0 + 0j
for j in range(n):
if j != i:
den *= z[i] - z[j]
if den == 0:
z[i] += 1e-8 * (1 + abs(z[i])) * cmath.exp(1j * (i + 1))
worst = 1.0
continue
d = polyval(a, z[i]) / den
z[i] -= d
worst = max(worst, abs(d) / (1.0 + abs(z[i])))
if worst < tol:
break
dp = polyder(a)
for i in range(n):
zi = z[i]
fz = abs(polyval(a, zi))
for _ in range(5):
der = polyval(dp, zi)
if der == 0 or fz == 0:
break
step = polyval(a, zi) / der
if abs(step) > 1e-6 * (1.0 + abs(zi)):
break
znew = zi - step
fnew = abs(polyval(a, znew))
if fnew >= fz:
break
zi, fz = znew, fnew
z[i] = zi
z = z + [0j] * origin
if real_coeffs:
thr = 1e-9
upper = [v for v in z if v.imag > thr * (1 + abs(v))]
lower = [v for v in z if v.imag < -thr * (1 + abs(v))]
reals = [complex(v.real, 0.0) for v in z if abs(v.imag) <= thr * (1 + abs(v))]
# A cluster of close roots can leave more roots above the real axis
# than below it (or the other way). The extra roots nearest to the
# axis are then taken as real, so the output is closed under
# conjugation.
if len(upper) < len(lower):
upper, lower = [v.conjugate() for v in lower], [v.conjugate() for v in upper]
upper.sort(key=lambda v: v.imag)
extra = len(upper) - len(lower)
reals += [complex(v.real, 0.0) for v in upper[:extra]]
upper = upper[extra:]
out = list(reals)
rest = list(lower)
for u in upper:
w = min(rest, key=lambda v: abs(v - u.conjugate()))
rest.remove(w)
re = (u.real + w.real) / 2
im = (u.imag - w.imag) / 2
out.append(complex(re, im))
out.append(complex(re, -im))
z = out
return sorted(z, key=lambda v: (v.real, v.imag))
def _norm_inf(a):
return max((sum(abs(v) for v in row) for row in a), default=0.0)
def expm(a):
"""Return e^A in floating point by scaling and squaring with a Taylor series.
A is scaled by 2^-s so that its infinity norm is at most 1/2, the Taylor
series of the scaled matrix is summed until a term is below 2^-60 of the
sum, and the result is squared s times. Entries of the result are float
(complex if A has complex entries).
"""
n, m = _shape(a)
if n != m:
raise ValueError("expm: matrix is not square")
cplx = any(isinstance(v, complex) for row in a for v in row)
conv = complex if cplx else float
x = [[conv(v) for v in row] for row in a]
nrm = _norm_inf(x)
s = 0
while nrm > 0.5:
nrm /= 2.0
s += 1
x = scale(conv(2.0 ** -s), x)
e = [[conv(1.0 if i == j else 0.0) for j in range(n)] for i in range(n)]
term = [row[:] for row in e]
for k in range(1, 60):
term = scale(1.0 / k, mul(term, x))
e = add(e, term)
tn = _norm_inf(term)
if tn == 0.0 or tn <= 2.0 ** -60 * _norm_inf(e):
break
for _ in range(s):
e = mul(e, e)
return e
def mat_power(a, k):
"""Return A^k for an int k by repeated squaring (A^0 = I; k < 0 uses inv)."""
n, m = _shape(a)
if n != m:
raise ValueError("mat_power: matrix is not square")
if k < 0:
a = inv(a)
k = -k
result = eye(n)
base = [list(row) for row in a]
while k:
if k & 1:
result = mul(result, base)
k >>= 1
if k:
base = mul(base, base)
return result
def is_symmetric(a, tol=0):
"""Return True if a is square and |a_ij - a_ji| <= tol for all i, j."""
n, m = _shape(a)
if n != m:
return False
return all(abs(a[i][j] - a[j][i]) <= tol for i in range(n) for j in range(i + 1, n))
def is_pos_def(a, margin=0):
"""Return True if a is symmetric and a - margin I is positive definite.
With int and Fraction entries (and an exact margin) the test is exact:
every leading principal minor of a - margin I must be positive
(Sylvester's criterion), computed in Fraction. With float entries the
matrix must be symmetric within 1e-12 times its largest entry, and the
Cholesky factorization of a - margin I must have positive pivots.
Complex entries are not accepted.
"""
n, m = _shape(a)
if n != m:
return False
if any(isinstance(v, complex) for row in a for v in row):
raise ValueError("is_pos_def: complex entries are not accepted")
if _all_exact(a) and _is_exact(margin):
b = [[Fraction(a[i][j]) - (Fraction(margin) if i == j else 0) for j in range(n)] for i in range(n)]
if not is_symmetric(b):
return False
return all(det([row[:k] for row in b[:k]]) > 0 for k in range(1, n + 1))
b = [[float(a[i][j]) - (float(margin) if i == j else 0.0) for j in range(n)] for i in range(n)]
big = max((abs(float(v)) for row in a for v in row), default=0.0)
if not is_symmetric(b, 1e-12 * max(big, 1e-300)):
return False
low = [[0.0] * n for _ in range(n)]
for j in range(n):
d = b[j][j] - sum(low[j][k] ** 2 for k in range(j))
if not d > 0.0:
return False
low[j][j] = math.sqrt(d)
for i in range(j + 1, n):
low[i][j] = (b[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
return True
def _self_test():
a = [[0, 1], [-2, -3]]
assert charpoly(a) == [1, 3, 2]
assert det(a) == 2
assert mul(inv(a), a) == eye(2)
assert solve(a, [1, 0]) == [Fraction(-3, 2), Fraction(1)]
r = polyroots([1, 3, 2])
assert abs(r[0] + 2) < 1e-12 and abs(r[1] + 1) < 1e-12
t = 0.7
e = expm([[0.0, t], [-t, 0.0]])
want = [[math.cos(t), math.sin(t)], [-math.sin(t), math.cos(t)]]
assert max(abs(e[i][j] - want[i][j]) for i in range(2) for j in range(2)) < 1e-14
assert is_pos_def([[Fraction(5, 4), Fraction(1, 4)], [Fraction(1, 4), Fraction(1, 4)]])
assert not is_pos_def([[1, 2], [2, 1]])
assert abs(norm2([[3.0, 0.0], [0.0, -4.0]]) - 4.0) < 1e-12
return True
if __name__ == "__main__":
_self_test()
jury.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/jury-stability-test/. The authors are listed in prov/7A0696.jsonl.
"""The Jury stability test for a real polynomial, in exact arithmetic.
A polynomial is a list of coefficients, highest power first:
[a0, a1, ..., an] is a0 z^n + a1 z^(n-1) + ... + an. The entries may be int,
Fraction or float; floats are converted exactly to Fraction, so the verdict
is exact for the polynomial whose coefficients are the given numbers.
jury_table follows the pseudocode of the page (lines L1 to L9). Each pass
removes the constant term of p_k with a multiple of the reversed polynomial
and divides by z. The first column F holds the leading coefficients of p_n,
p_(n-1), ..., p_0. If no entry of F is zero, the number of negative entries
is the number of roots outside the closed unit disc, and p is Schur (all
roots inside the open unit disc) exactly when that number is 0. A zero entry
is a singular step; p is then not Schur.
jury_classic checks the n + 1 conditions of the table of Jury and Blanchard:
p(1) > 0, (-1)^n p(-1) > 0, |an| < a0, and |lead| > |const| for the reduced
polynomials of degree n - 1 down to 2. It uses the division-free rows.
"""
from dataclasses import dataclass, field
from fractions import Fraction
from typing import List, Optional
@dataclass
class JuryResult:
"""The outcome of jury_table.
first: the first column a_0^n, a_0^(n-1), ..., a_0^j (as far as computed).
rows: the coefficient lists of p_n, p_(n-1), ... (highest power first).
alphas: alpha_n, alpha_(n-1), ... .
outside: the number of roots outside the closed unit disc, or None if
the table is singular.
regular: False if some entry of the first column is zero.
schur: True if every root lies in the open unit disc.
"""
first: List[Fraction]
rows: List[List[Fraction]]
alphas: List[Fraction] = field(default_factory=list)
outside: Optional[int] = None
regular: bool = True
schur: bool = False
def _exact(v):
if isinstance(v, (int, Fraction)):
return Fraction(v)
if isinstance(v, float):
return Fraction(v)
raise TypeError("coefficients must be int, Fraction or float")
def _normalize(p):
c = [_exact(v) for v in p]
while c and c[0] == 0:
c.pop(0)
if not c:
raise ValueError("the zero polynomial has no Jury table")
return c
def jury_table(p):
"""Build the Jury table of p and return a JuryResult."""
c = _normalize(p) # @line L1
if c[0] < 0: # @line L1
c = [-v for v in c] # @line L1
n = len(c) - 1
first = [c[0]] # @line L2
rows = [list(c)] # @line L2
alphas = []
for k in range(n, 0, -1): # @line L3
alpha = c[k] / c[0] # @line L4
alphas.append(alpha)
c = [c[i] - alpha * c[k - i] for i in range(k)] # @line L5
first.append(c[0]) # @line L6
rows.append(list(c))
if c[0] == 0: # @line L7
return JuryResult(first, rows, alphas, None, False, False) # @line L7
neg = sum(1 for v in first if v < 0) # @line L8
return JuryResult(first, rows, alphas, neg, True, neg == 0) # @line L9
def is_schur(p):
"""Return True if every root of p lies in the open unit disc."""
return jury_table(p).schur
def outside_count(p):
"""Return the number of roots outside the closed unit disc, or None."""
return jury_table(p).outside
def _polyval(c, x):
s = Fraction(0)
for v in c:
s = s * x + v
return s
def jury_classic(p):
"""Return True if the n + 1 conditions of the classic Jury table hold.
The rows are formed without division: from the coefficients c of degree
k, the next row has the entries c_0 c_i - c_k c_(k-i), i = 0..k-1, which
are c_0 times the entries of jury_table. The conditions are
p(1) > 0, (-1)^n p(-1) > 0, |c_k| < c_0 for the first row, and
|lead| > |const| for the rows of degree n - 1 down to 2.
"""
c = _normalize(p)
if c[0] < 0:
c = [-v for v in c]
n = len(c) - 1
if n == 0:
return True
if not _polyval(c, 1) > 0:
return False
if not (-1) ** n * _polyval(c, -1) > 0:
return False
if not abs(c[n]) < c[0]:
return False
for k in range(n, 2, -1):
c = [c[0] * c[i] - c[k] * c[k - i] for i in range(k)]
if not abs(c[0]) > abs(c[k - 1]):
return False
return True
jury_stability_test.py 14 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/jury-stability-test/. The authors are listed in prov/7A0696.jsonl.
"""The Jury stability test. The code is in jury.py; this module re-exports it
under the name of the page (a file name ending in _test is read as a test file
by some tools, so the implementation itself lives in jury.py)."""
from jury import ( # noqa: F401
JuryResult,
is_schur,
jury_classic,
jury_table,
outside_count,
)
test_jury_stability_test.py 202 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/jury-stability-test/. The authors are listed in prov/7A0696.jsonl.
import math
import random
from fractions import Fraction as F
import pytest
import ctlmat as cm
from jury_stability_test import is_schur, jury_classic, jury_table, outside_count
# A root with ||z| - 1| below EDGE is taken to be too close to the unit
# circle for a floating point check, and the polynomial is skipped.
EDGE = 1e-6
def moduli(c):
return [abs(z) for z in cm.polyroots([float(v) for v in c])]
def random_poly(rng, max_degree=6, lo=-4, hi=4):
n = rng.randint(1, max_degree)
c = [rng.randint(lo, hi) for _ in range(n + 1)]
while c[0] == 0:
c[0] = rng.randint(lo, hi)
return c
def poly_from_roots(roots):
c = [F(1)]
for r in roots:
c = cm.polymul(c, [F(1), -r])
return c
def test_check_value_trace():
# z^2 - z + 0.5 has both roots of modulus 1/sqrt(2).
r = jury_table([1, -1, F(1, 2)])
assert r.rows == [[1, -1, F(1, 2)], [F(3, 4), F(-1, 2)], [F(5, 12)]]
assert r.first == [1, F(3, 4), F(5, 12)]
assert r.alphas == [F(1, 2), F(-2, 3)]
assert r.regular and r.schur and r.outside == 0
assert all(abs(m - 1 / math.sqrt(2)) < 1e-12 for m in moduli([1, -1, 0.5]))
def test_cubic_with_one_root_outside():
# 4z^3 + 4z^2 - 7z + 2 = 4 (z - 1/2)^2 (z + 2)
r = jury_table([4, 4, -7, 2])
assert r.rows == [[4, 4, -7, 2], [3, F(15, 2), -9], [-24, 30], [F(27, 2)]]
assert r.first == [4, 3, -24, F(27, 2)]
assert r.outside == 1 and not r.schur
assert not jury_classic([4, 4, -7, 2])
def test_degree_two_triangle():
# z^2 + a1 z + a2 is Schur iff |a2| < 1 and |a1| < 1 + a2.
vals = [F(i, 4) for i in range(-12, 13)]
for a1 in vals:
for a2 in vals:
boundary = abs(a2) == 1 or abs(a1) == 1 + a2
want = abs(a2) < 1 and abs(a1) < 1 + a2
r = jury_table([1, a1, a2])
assert r.schur == want
assert jury_classic([1, a1, a2]) == want
if boundary and abs(a2) <= 1:
assert not r.regular
def test_random_against_roots():
rng = random.Random(20261115)
checked = 0
for _ in range(1500):
c = random_poly(rng)
ms = moduli(c)
if any(abs(m - 1) < EDGE for m in ms):
continue
r = jury_table(c)
out = sum(1 for m in ms if m > 1)
assert r.schur == (out == 0)
assert jury_classic(c) == (out == 0)
if r.regular:
assert r.outside == out
checked += 1
assert checked > 1000
def test_schur_polynomials_are_regular():
rng = random.Random(7)
for _ in range(300):
n = rng.randint(1, 6)
roots = []
while len(roots) < n:
rad = F(rng.randint(0, 99), 100)
if len(roots) <= n - 2 and rng.random() < 0.5:
# a conjugate pair, the roots of z^2 - 2 rad x z + rad^2
# with |x| < 1, both of modulus rad
x = F(rng.randint(-99, 99), 100)
roots.append(("pair", rad, x))
roots.append(None)
else:
roots.append(rad if rng.random() < 0.5 else -rad)
c = [F(1)]
for r in roots:
if r is None:
continue
if isinstance(r, tuple):
_, rad, x = r
c = cm.polymul(c, [F(1), -2 * rad * x, rad * rad])
else:
c = cm.polymul(c, [F(1), -r])
res = jury_table(c)
assert res.regular and res.schur and res.outside == 0
assert jury_classic(c)
def test_regular_count_outside_with_random_roots():
rng = random.Random(11)
for _ in range(300):
n = rng.randint(1, 6)
roots = []
for _ in range(n):
if rng.random() < 0.5:
roots.append(F(rng.randint(-95, 95), 100))
else:
v = F(rng.randint(105, 400), 100)
roots.append(v if rng.random() < 0.5 else -v)
# avoid reciprocal pairs, which make the table singular
if any(a * b == 1 for i, a in enumerate(roots) for b in roots[i + 1:]):
continue
c = poly_from_roots(roots)
r = jury_table(c)
if r.regular:
assert r.outside == sum(1 for v in roots if abs(v) > 1)
else:
assert sum(1 for v in roots if abs(v) > 1) > 0
def test_singular_cases():
# a root on the circle
r = jury_table([1, F(-3, 2), F(1, 2)]) # (z - 1)(z - 1/2)
assert not r.regular and not r.schur and r.outside is None
assert r.first == [1, F(3, 4), 0]
# a reciprocal pair, no root on the circle
r = jury_table([1, F(-5, 2), 1]) # (z - 2)(z - 1/2)
assert not r.regular and r.first == [1, 0]
r = jury_table([8, -18, 3, 2]) # (z - 2)(2z - 1)(4z + 1)
assert not r.regular and r.first == [8, F(15, 2), 0]
# roots at -1 and on the circle at +-i
assert not jury_table([1, 0, 1]).regular
assert not is_schur([1, 1])
def test_relation_to_schur_cohn_transform():
# p_(k-1) is the Schur transform of p_k, reversed and scaled by -1/c_0.
rng = random.Random(3)
for _ in range(200):
c = [F(v) for v in random_poly(rng)]
if c[0] < 0:
c = [-v for v in c]
r = jury_table(c)
for pk, pk1 in zip(r.rows, r.rows[1:]):
k = len(pk) - 1
star = pk[::-1]
t = [pk[k] * pk[i] - pk[0] * star[i] for i in range(k + 1)]
assert t[0] == 0
tail = t[1:] # degree k - 1, highest power first
assert [-v / pk[0] for v in tail[::-1]] == pk1
def test_input_handling():
assert jury_table([0, 0, 1, F(-1, 2)]).schur # leading zeros removed
assert jury_table([-1, 1, F(-1, 2)]).schur # negative leading coefficient
assert jury_table([-2, 1, 3]).outside == outside_count([2, -1, -3])
assert jury_table([5]).schur and jury_table([5]).outside == 0
assert jury_table([1.0, -1.0, 0.5]).first == [1, F(3, 4), F(5, 12)]
with pytest.raises(ValueError):
jury_table([0, 0])
with pytest.raises(TypeError):
jury_table([1, "a"])
def test_gain_range_of_a_sampled_loop():
# z^2 - e^-1 z + K (1 - e^-1): Schur for 0 < K < 1 / (1 - e^-1) = 1.58198.
a = math.exp(-1)
b = 1 - a
kmax = 1 / b
assert abs(kmax - 1.58198) < 1e-5
for k in [0.01, 0.5, 1.0, 1.5, kmax * (1 - 1e-9)]:
assert is_schur([1.0, -a, k * b])
for k in [kmax * (1 + 1e-9), 1.6, 3.0]:
assert not is_schur([1.0, -a, k * b])
assert outside_count([1.0, -a, k * b]) == 2
def test_degree_drops_by_one():
rng = random.Random(5)
for _ in range(100):
c = random_poly(rng)
r = jury_table(c)
n = len(c) - 1 # random_poly gives a nonzero leading coefficient
assert [len(row) - 1 for row in r.rows] == list(range(n, n - len(r.rows), -1))
History
Issai Schur studied in 1917 and 1918 the transform that lowers the degree of a polynomial with its reversed polynomial, and Arthur Cohn used it in 1922 to count the roots of a polynomial in a circle. Eliahu I. Jury and J. Blanchard put the recursion for real polynomials into a table with sign and modulus conditions in 1961, and Jury's book of 1964 on the z-transform made the table the standard stability test for sampled-data control systems. Control textbooks present it in two forms: the division-free table with conditions, as in Ogata, and the normalized table whose first column counts the roots outside the circle, as in Åström and Wittenmark.
References
- E. I. Jury and J. Blanchard, A stability test for linear discrete systems in table form, Proceedings of the IRE 49(12), 1947-1948, 1961, the table of the coefficients and the inequalities that decide whether all roots lie inside the unit circle
- E. I. Jury, Theory and Application of the z-Transform Method, Wiley, 1964, the stability test for discrete-time systems in table form
- Karl J. Åström and Björn Wittenmark, Computer-Controlled Systems, Theory and Design, third edition, Prentice Hall, 1997, Chapter 3, Analysis of Discrete-Time Systems (Jury's stability criterion)
- Katsuhiko Ogata, Discrete-Time Control Systems, second edition, Prentice Hall, 1995, Chapter 4 (the Jury stability test in the classic form, with its necessary conditions at z = 1 and z = -1)
- A. Cohn, Über die Anzahl der Wurzeln einer algebraischen Gleichung in einem Kreise, Mathematische Zeitschrift 14 (1922) 110-148, the reduction of the degree by the reversed polynomial, which the table puts in rows
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 7A0696 Edit this page History Report an error Markdown