Algorithm Search⌘K

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
Properties
deterministicexactiterative
Origin
Eliahu I. Jury, J. Blanchard, 1961

The Jury stability test decides whether every root of a real polynomial p(z)p(z) lies inside the open unit circle, that is, whether pp 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 pp is the characteristic polynomial of a discrete-time linear system xk+1=Axkx_{k+1} = A x_k, or the denominator of a closed-loop transfer function in the variable zz of the z-transform, the test decides whether AA 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 p(z)=a0zn+a1zn−1+⋯+anp(z) = a_0 z^n + a_1 z^{n-1} + \dots + a_n with a0≠0a_0 \ne 0, written with the highest power first, decide whether all its roots satisfy ∣z∣<1|z| < 1. When the answer is no, count the roots with ∣z∣>1|z| > 1, counted with multiplicity, if the table allows it.

A matrix is Schur if every eigenvalue has modulus less than 11, and a polynomial is Schur in the same sense for its roots. The usual source of pp is det⁡(zI−A)\det(zI - A) for the matrix AA of a discrete-time model, for example the zero-order hold model Ad=eAhA_d = e^{A h} of a continuous plant with sampling period hh, or the closed-loop characteristic polynomial of a sampled-data system.

Notation. pkp_k is the polynomial of degree kk in the table, with coefficients c0,…,ckc_0, \dots, c_k (highest power first). Its reversed polynomial is pk∗(z)=zkpk(1/z)=ckzk+⋯+c0p_k^*(z) = z^k p_k(1/z) = c_k z^k + \dots + c_0. The number αk=ck/c0\alpha_k = c_k / c_0 is the reflection coefficient of step kk, and FF is the first column: the leading coefficients of pn,pn−1,…,p0p_n, p_{n-1}, \dots, p_0.

The algorithm

  1. JURY(a_0, ..., a_n) ▷ p(z) = a_0 z^n + ... + a_n, real
  2. 1remove zero leading coefficients (error if none is left); if a_0 < 0 then negate every a_i
  3. 2c ← (a_0, ..., a_n); F ← (a_0)
  4. 3for k ← n down to 1 do ▷ c holds the k + 1 coefficients of p_k
  5. 4α_k ← c_k / c_0
  6. 5c ← (c_i - α_k · c_{k-i} for i = 0, ..., k - 1) ▷ p_{k-1}: (p_k - α_k p_k*) / z
  7. 6append c_0 to F
  8. 7if c_0 = 0 then return (F, "singular") ▷ |α_k| = 1: p is not Schur
  9. 8N ← the number of negative entries of F
  10. 9return (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 αk\alpha_k times the reversed row from the row. The last entry becomes ck−αkc0=0c_k - \alpha_k c_0 = 0, so the result is z pk−1(z)=pk(z)−αkpk∗(z)z\,p_{k-1}(z) = p_k(z) - \alpha_k p_k^*(z), and the new leading coefficient is c0(1−αk2)c_0 (1 - \alpha_k^2). So the first entry keeps its sign when ∣αk∣<1|\alpha_k| < 1, changes its sign when ∣αk∣>1|\alpha_k| > 1, and is zero when ∣αk∣=1|\alpha_k| = 1. Line L7 stops on a zero entry. In a printed Jury table each polynomial pkp_k takes two rows, the coefficients and their reverse, so the table has 2n+12n + 1 rows.

The implementation computes in exact rational arithmetic and converts floating point input exactly. It returns the rows, the first column, the numbers αk\alpha_k, the count NN (or "singular"), and the verdict. It also has the classic n+1n + 1 conditions of Jury and Blanchard (see Variants) as a second, independent check.

Example

The check value. For p(z)=z2−z+0.5p(z) = z^2 - z + 0.5:

row entries αk\alpha_k
p2p_2 11, −1-1, 1/21/2 α2=1/2\alpha_2 = 1/2
p2∗p_2^* 1/21/2, −1-1, 11
p1p_1 1−12⋅12=3/41 - \frac12 \cdot \frac12 = 3/4, −1−12⋅(−1)=−1/2-1 - \frac12 \cdot (-1) = -1/2 α1=−2/3\alpha_1 = -2/3
p1∗p_1^* −1/2-1/2, 3/43/4
p0p_0 3/4−(−23)(−12)=5/123/4 - (-\frac23)(-\frac12) = 5/12

The first column 1,3/4,5/121, 3/4, 5/12 is positive, so pp is Schur. Indeed the roots are 0.5±0.5i0.5 \pm 0.5 i, both of modulus 1/2=0.707111/\sqrt 2 = 0.70711.

One root outside. For p(z)=4z3+4z2−7z+2=4(z−12)2(z+2)p(z) = 4 z^3 + 4 z^2 - 7 z + 2 = 4 (z - \frac12)^2 (z + 2) the rows are (4,4,−7,2)(4, 4, -7, 2), then with α3=1/2\alpha_3 = 1/2 the row (3,15/2,−9)(3, 15/2, -9), then with α2=−3\alpha_2 = -3 the row (−24,30)(-24, 30), then with α1=−5/4\alpha_1 = -5/4 the row (27/2)(27/2). The first column 4,3,−24,27/24, 3, -24, 27/2 has one negative entry, so one root lies outside the circle: the root −2-2. The double root 1/21/2 causes no difficulty.

A gain range. Take the plant 1/(s+1)1/(s + 1), with time in seconds, sampled with a zero-order hold at h=1h = 1 s, a delay of one sample for the computation, and the controller uk=Keku_k = K e_k. The loop transfer function is L(z)=Kb/(z(z−a))L(z) = K b / (z (z - a)) with a=e−1=0.36788a = e^{-1} = 0.36788 and b=1−e−1=0.63212b = 1 - e^{-1} = 0.63212, and the closed-loop polynomial is z2−az+Kbz^2 - a z + K b. For a general z2+a1z+a2z^2 + a_1 z + a_2 the table gives α2=a2\alpha_2 = a_2, the first entry 1−a221 - a_2^2, then α1=a1/(1+a2)\alpha_1 = a_1 / (1 + a_2). The first column is positive exactly when

∣a2∣<1,∣a1∣<1+a2,|a_2| < 1, \qquad |a_1| < 1 + a_2 ,

the well known stability triangle. Here this gives −1<K<1/b=1.58198-1 < K < 1/b = 1.58198. At K=1.58198K = 1.58198 the two closed-loop poles are on the unit circle at the angle arccos⁡(a/2)=1.3858\arccos(a/2) = 1.3858 rad. The continuous loop without the sample and the delay would be asymptotically stable for every K>−1K > -1; the sampling and the delay create the upper limit.

Singular tables. For (z−1)(z−12)=z2−32z+12(z - 1)(z - \frac12) = z^2 - \frac32 z + \frac12 the first column is 1,3/4,01, 3/4, 0: a root on the circle. For (z−2)(z−12)=z2−52z+1(z - 2)(z - \frac12) = z^2 - \frac52 z + 1 it is 1,01, 0 at once, because α2=1\alpha_2 = 1. This polynomial has no root on the circle, but its two roots are mirror images in the circle. The cubic 8z3−18z2+3z+2=(z−2)(2z−1)(4z+1)8 z^3 - 18 z^2 + 3 z + 2 = (z - 2)(2 z - 1)(4 z + 1) gives 8,15/2,08, 15/2, 0 for the same reason.

Correctness

The proofs are in the correctness proof.

  • One step (proved). If pkp_k has no root on the circle and ∣αk∣≠1|\alpha_k| \ne 1, then pk−1p_{k-1} has no root on the circle. It has as many roots outside the circle as pkp_k when ∣αk∣<1|\alpha_k| < 1, and kk minus that number when ∣αk∣>1|\alpha_k| > 1. The proof uses ∣pk∗(z)∣=∣pk(z)∣|p_k^*(z)| = |p_k(z)| on the circle and Rouché's theorem.
  • The count (proved). If no entry of FF is zero, pp has no root on the circle, and the number of negative entries of FF is the number of roots outside the circle. So pp is Schur exactly when every entry is positive.
  • Singular tables (proved). A root on the circle, or a pair of roots ζ\zeta and 1/ζ1/\zeta, always gives a zero entry. A Schur polynomial never gives one, so a singular table means that pp is not Schur. The count is not available in that case.
  • The classic conditions (proved). For a0>0a_0 > 0 and n≥2n \ge 2, pp is Schur if and only if p(1)>0p(1) > 0, (−1)np(−1)>0(-1)^n p(-1) > 0 and ∣αk∣<1|\alpha_k| < 1 for k=n,…,2k = n, \dots, 2.
  • Termination (proved). Each pass shortens the row by one, so there are at most nn 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 −4-4 to 44, skipping those with a root within 10−610^{-6} 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 p(z)=a0zn+a1zn−1+⋯+anp(z) = a_0 z^n + a_1 z^{n-1} + \dots + a_n be real with a0>0a_0 > 0 (line L1 makes a0a_0 positive; multiplying pp by −1-1 changes no root). The arithmetic is exact. For a real polynomial qq of exact degree kk, let q∗(z)=zkq(1/z)q^*(z) = z^k q(1/z) be the reversed polynomial (the same coefficients in the opposite order). Write D={∣z∣<1}\mathbb{D} = \{|z| < 1\} and T={∣z∣=1}\mathbb{T} = \{|z| = 1\}. For qq with no root on T\mathbb{T}, in⁡(q)\operatorname{in}(q) and out⁡(q)\operatorname{out}(q) are the numbers of roots of qq in D\mathbb{D} and outside D‾\overline{\mathbb{D}}, counted with multiplicity, so in⁡(q)+out⁡(q)=deg⁡q\operatorname{in}(q) + \operatorname{out}(q) = \deg q.

The algorithm computes pn=pp_n = p and, while the leading coefficient c0c_0 of pkp_k is not zero, αk=ck/c0\alpha_k = c_k / c_0 and

z pk−1(z)=pk(z)−αk pk∗(z),(1)z\, p_{k-1}(z) = p_k(z) - \alpha_k\, p_k^*(z), \qquad (1)

whose coefficients are ci−αkck−ic_i - \alpha_k c_{k-i}, i=0,…,k−1i = 0, \dots, k-1 (line L5). The first column is F=(fn,fn−1,… )F = (f_n, f_{n-1}, \dots) with fkf_k the leading coefficient of pkp_k.

Lemma 1: one step

Let pkp_k have exact degree k≥1k \ge 1, leading coefficient fk≠0f_k \ne 0 and constant term ckc_k.

(a) The right side of (1) has constant term 00, so pk−1p_{k-1} is a polynomial of degree at most k−1k - 1, and its coefficient of zk−1z^{k-1} is fk−1=fk(1−αk2)f_{k-1} = f_k (1 - \alpha_k^2).

(b) fk−1f_{k-1} has the sign of fkf_k if ∣αk∣<1|\alpha_k| < 1, the opposite sign if ∣αk∣>1|\alpha_k| > 1, and fk−1=0f_{k-1} = 0 if ∣αk∣=1|\alpha_k| = 1.

(c) If pkp_k has no root on T\mathbb{T} and ∣αk∣≠1|\alpha_k| \ne 1, then pk−1p_{k-1} has exact degree k−1k - 1, no root on T\mathbb{T}, and

out⁡(pk−1)=out⁡(pk) if ∣αk∣<1,out⁡(pk−1)=k−out⁡(pk) if ∣αk∣>1.\operatorname{out}(p_{k-1}) = \operatorname{out}(p_k) \text{ if } |\alpha_k| < 1, \qquad \operatorname{out}(p_{k-1}) = k - \operatorname{out}(p_k) \text{ if } |\alpha_k| > 1 .

Proof. (a) The constant term of pk∗p_k^* is fkf_k, so the constant term of the right side is ck−αkfk=0c_k - \alpha_k f_k = 0. The leading coefficient of pk∗p_k^* is ckc_k, so the coefficient of zkz^k on the right side is fk−αkck=fk−ck2/fk=fk(1−αk2)f_k - \alpha_k c_k = f_k - c_k^2 / f_k = f_k(1 - \alpha_k^2). (b) follows from (a).

(c) By (b), fk−1≠0f_{k-1} \ne 0, so deg⁡pk−1=k−1\deg p_{k-1} = k - 1. For z∈Tz \in \mathbb{T}, 1/z=zˉ1/z = \bar z, and since the coefficients are real, pk(zˉ)=pk(z)‾p_k(\bar z) = \overline{p_k(z)}. So ∣pk∗(z)∣=∣zk∣ ∣pk(zˉ)∣=∣pk(z)∣|p_k^*(z)| = |z^k|\,|p_k(\bar z)| = |p_k(z)| on T\mathbb{T}, and this is positive because pkp_k has no root on T\mathbb{T}.

If ∣αk∣<1|\alpha_k| < 1, then ∣αkpk∗(z)∣<∣pk(z)∣|\alpha_k p_k^*(z)| < |p_k(z)| on T\mathbb{T}. So ∣zpk−1(z)∣≥(1−∣αk∣)∣pk(z)∣>0|z p_{k-1}(z)| \ge (1 - |\alpha_k|)|p_k(z)| > 0 on T\mathbb{T}, and by Rouché's theorem zpk−1z p_{k-1} and pkp_k have the same number of roots in D\mathbb{D}. The factor zz adds the root 00, so in⁡(pk−1)=in⁡(pk)−1\operatorname{in}(p_{k-1}) = \operatorname{in}(p_k) - 1, and out⁡(pk−1)=(k−1)−in⁡(pk−1)=k−in⁡(pk)=out⁡(pk)\operatorname{out}(p_{k-1}) = (k - 1) - \operatorname{in}(p_{k-1}) = k - \operatorname{in}(p_k) = \operatorname{out}(p_k).

If ∣αk∣>1|\alpha_k| > 1, then ∣pk(z)∣<∣αkpk∗(z)∣|p_k(z)| < |\alpha_k p_k^*(z)| on T\mathbb{T}, zpk−1z p_{k-1} has no root on T\mathbb{T}, and by Rouché's theorem zpk−1z p_{k-1} has as many roots in D\mathbb{D} as pk∗p_k^*. The roots of pk∗p_k^* are the reciprocals 1/ζ1/\zeta of the roots ζ\zeta of pkp_k (none of which is 00, because pk∗p_k^* has degree kk only if ck≠0c_k \ne 0, and ∣αk∣>1|\alpha_k| > 1 gives ck≠0c_k \ne 0), with the same multiplicities. So in⁡(pk∗)=out⁡(pk)\operatorname{in}(p_k^*) = \operatorname{out}(p_k). Then in⁡(pk−1)=out⁡(pk)−1\operatorname{in}(p_{k-1}) = \operatorname{out}(p_k) - 1 and out⁡(pk−1)=k−1−out⁡(pk)+1=k−out⁡(pk)\operatorname{out}(p_{k-1}) = k - 1 - \operatorname{out}(p_k) + 1 = k - \operatorname{out}(p_k). □\square

Lemma 2: a root on the circle makes the table singular

If pp has a root ζ∈T\zeta \in \mathbb{T}, then some entry of FF is zero.

Proof. Suppose that pk(ζ)=0p_k(\zeta) = 0 and pkp_k has exact degree kk. Then pk∗(ζ)=ζkpk(ζˉ)=ζk pk(ζ)‾=0p_k^*(\zeta) = \zeta^k p_k(\bar\zeta) = \zeta^k\, \overline{p_k(\zeta)} = 0, and by (1), pk−1(ζ)=0p_{k-1}(\zeta) = 0 because ζ≠0\zeta \ne 0. If no entry of FF were zero, every pkp_k would have exact degree kk, and by induction p0(ζ)=0p_0(\zeta) = 0. But p0p_0 is the nonzero constant f0f_0. This is a contradiction. □\square

The same argument shows that a pair of roots ζ\zeta and 1/ζ1/\zeta of pp (a common root of pp and p∗p^*) also makes the table singular.

Theorem

The loop runs at most nn times. Let the algorithm return.

(i) If no entry of FF is zero (the regular case), then pp has no root on T\mathbb{T}, and the number NN of negative entries of FF equals out⁡(p)\operatorname{out}(p). In particular pp is Schur if and only if N=0N = 0.

(ii) If some entry of FF is zero (the singular case), then pp is not Schur.

Proof. Termination: each pass lowers the length of the coefficient list by exactly one, so there are at most nn passes.

(i) By Lemma 2, pp has no root on T\mathbb{T}. Since every fk≠0f_k \ne 0, Lemma 1(b) gives ∣αk∣≠1|\alpha_k| \ne 1 for every kk, and Lemma 1(c) applies at every step. Let sks_k be the sign of fkf_k and let ckc_k be the number of indices j<kj < k with sj≠sks_j \ne s_k. We show out⁡(pk)=ck\operatorname{out}(p_k) = c_k by induction on kk. For k=0k = 0, p0p_0 is a nonzero constant, and out⁡(p0)=0=c0\operatorname{out}(p_0) = 0 = c_0. Let k≥1k \ge 1.

  • If ∣αk∣<1|\alpha_k| < 1, then sk−1=sks_{k-1} = s_k by Lemma 1(b), so ck=ck−1c_k = c_{k-1}, and out⁡(pk)=out⁡(pk−1)=ck−1=ck\operatorname{out}(p_k) = \operatorname{out}(p_{k-1}) = c_{k-1} = c_k by Lemma 1(c).
  • If ∣αk∣>1|\alpha_k| > 1, then sk−1=−sks_{k-1} = -s_k. Index k−1k - 1 counts in ckc_k, and an index j<k−1j < k - 1 counts in ckc_k exactly when sj=sk−1s_j = s_{k-1}. So ck=1+(k−1−ck−1)=k−ck−1c_k = 1 + (k - 1 - c_{k-1}) = k - c_{k-1}. By Lemma 1(c), out⁡(pk)=k−out⁡(pk−1)=k−ck−1=ck\operatorname{out}(p_k) = k - \operatorname{out}(p_{k-1}) = k - c_{k-1} = c_k.

For k=nk = n, sn=+1s_n = +1 because a0>0a_0 > 0, so cnc_n is the number of negative entries of FF, which is NN.

(ii) Let fk−1=0f_{k-1} = 0 be the first zero entry, so ∣αk∣=1|\alpha_k| = 1 and ∣ck∣=∣fk∣|c_k| = |f_k|, where ckc_k is the constant term of pkp_k. Suppose that pp is Schur. Then, by induction with Lemma 1, every pjp_j with j≥kj \ge k is Schur: pn=pp_n = p is Schur, and if pjp_j is Schur then ∣αj∣=∣cj/fj∣|\alpha_j| = |c_j / f_j| is the product of the moduli of the jj roots of pjp_j, which is less than 11, so Lemma 1(c) gives out⁡(pj−1)=out⁡(pj)=0\operatorname{out}(p_{j-1}) = \operatorname{out}(p_j) = 0. But then ∣αk∣<1|\alpha_k| < 1, which contradicts ∣αk∣=1|\alpha_k| = 1. So pp is not Schur. □\square

Corollary: the n + 1 conditions of the classic table

For a0>0a_0 > 0 and n≥2n \ge 2, pp is Schur if and only if p(1)>0p(1) > 0, (−1)np(−1)>0(-1)^n p(-1) > 0, and ∣αk∣<1|\alpha_k| < 1 for k=n,n−1,…,2k = n, n - 1, \dots, 2.

Proof. By the theorem and Lemma 1(b), pp is Schur if and only if ∣αk∣<1|\alpha_k| < 1 for k=n,…,1k = n, \dots, 1 (then all fkf_k are positive). At z=1z = 1, (1) gives pk−1(1)=pk(1)(1−αk)p_{k-1}(1) = p_k(1)(1 - \alpha_k), because pk∗(1)=pk(1)p_k^*(1) = p_k(1). At z=−1z = -1, pk∗(−1)=(−1)kpk(−1)p_k^*(-1) = (-1)^k p_k(-1), so pk−1(−1)=−pk(−1)(1−(−1)kαk)p_{k-1}(-1) = -p_k(-1)(1 - (-1)^k \alpha_k). If ∣αk∣<1|\alpha_k| < 1 for k=n,…,2k = n, \dots, 2, the factors 1∓αk1 \mp \alpha_k are positive. Then p1(1)p_1(1) has the sign of p(1)p(1), and −p1(−1)-p_1(-1) has the sign of (−1)np(−1)(-1)^n p(-1). The polynomial p1(z)=f1z+c1p_1(z) = f_1 z + c_1 has f1>0f_1 > 0, and ∣α1∣=∣c1∣/f1<1|\alpha_1| = |c_1| / f_1 < 1 holds if and only if p1(1)=f1+c1>0p_1(1) = f_1 + c_1 > 0 and −p1(−1)=f1−c1>0-p_1(-1) = f_1 - c_1 > 0. So, under ∣αk∣<1|\alpha_k| < 1 for k≥2k \ge 2, the condition ∣α1∣<1|\alpha_1| < 1 is equivalent to p(1)>0p(1) > 0 and (−1)np(−1)>0(-1)^n p(-1) > 0. If some ∣αk∣≥1|\alpha_k| \ge 1 with k≥2k \ge 2, both sides of the claim are false. □\square

The classic table forms the rows without the division by c0c_0, so each row is a positive or negative multiple of the row above, and the test ∣αk∣<1|\alpha_k| < 1 becomes ∣first entry∣>∣last entry∣|\text{first entry}| > |\text{last entry}|, 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 kk costs one division and kk multiplications and subtractions. In all this is nn divisions and n(n+1)/2n (n + 1)/2 multiplications, so O(n2)O(n^2) operations.
  • Space. O(n)O(n) numbers if only the current row and the first column are kept, and O(n2)O(n^2) 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 O(n2)O(n^2), but the cost in bit operations is higher.
  • Compared with root finding. Computing all roots and their moduli also costs O(n2)O(n^2) 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 KK.

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 pp by a positive number scales every row by that number and does not change FF in sign.
  • Reflection coefficients. pp is Schur if and only if ∣αk∣<1|\alpha_k| < 1 for every kk. The numbers αk\alpha_k 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 2×22 \times 2 determinants c0ci−ckck−ic_0 c_i - c_k c_{k-i}, and stops at the row of degree 2, so the table has 2n−32n - 3 rows. The test is then the n+1n + 1 conditions p(1)>0p(1) > 0, (−1)np(−1)>0(-1)^n p(-1) > 0, ∣an∣<a0|a_n| < a_0, and ∣first entry∣>∣last entry∣|\text{first entry}| > |\text{last entry}| 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 Tp=p(0)‾ p−lead⁡(p) p∗T p = \overline{p(0)}\, p - \operatorname{lead}(p)\, p^*, 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 pkp_k the row pk−1p_{k-1} is TpkT p_k in reversed order, multiplied by −1/c0-1/c_0. So the two tables carry the same polynomials, and they become singular for the same inputs.
  • The bilinear map. The substitution z=(1+w)/(1−w)z = (1 + w)/(1 - w) 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 pp, and needs fewer multiplications.
  • Margins inside the disc. To test whether all roots satisfy ∣z∣<r|z| < r, run the table on p(rz)p(r z). For the damping of a sampled loop, r<1r < 1 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 ATPA−P=−QA^T P A - P = -Q.

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 z2−52z+1z^2 - \frac52 z + 1 has the roots 22 and 12\frac12. The verdict "not Schur" is still correct, but the count needs another method, for example the table of p(rz)p(r z) for an rr slightly different from 11.
  • A negative leading coefficient. The count "number of negative entries" assumes a0>0a_0 > 0. Negate pp 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 z2−z+0.5z^2 - z + 0.5, 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: z2−z+0.5z^2 - z + 0.5 is Schur with a negative coefficient, and z+2z + 2 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.

ctlmat.pyI0RawGitHub
# 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 n+1n + 1 conditions, as in Ogata, and the normalized table whose first column counts the roots outside the circle, as in Åström and Wittenmark.

References

  1. 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
  2. E. I. Jury, Theory and Application of the z-Transform Method, Wiley, 1964, the stability test for discrete-time systems in table form
  3. 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)
  4. 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)
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • 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
  • a scene preset for the example