Algorithm Search⌘K

Algorithmintro

Routh array

Also called Routh table, Routh tabulation.

Builds a table from the coefficients of a polynomial by cross products, and counts its right half plane roots by the sign changes in the first column. O(n^2) operations.

Time
O(n^2) worst
Space
O(n^2) extra
Where
n = the degree of the polynomial
Properties
deterministicexactiterative
Origin
Edward John Routh, 1877

The Routh array is a table of numbers built from the coefficients of a real polynomial p(s)=a0sn+a1sn−1+⋯+anp(s) = a_0 s^n + a_1 s^{n-1} + \dots + a_n. The first two rows hold the coefficients with even and odd index, and each later row is made from the two rows above it by 2×22 \times 2 cross products. The number of sign changes in the first column of the table equals the number of roots of pp in the open right half plane, when the table has no zero in its first column. So the table tells whether a linear system with characteristic polynomial pp has a Hurwitz matrix without computing any root. The theorem behind it is the Routh-Hurwitz criterion; this page gives the algorithm, its two special cases, an exact implementation and its proof. The method needs about n2/4n^2/4 cross products, and it works with symbolic coefficients, which is why it is still used to find the gains that keep a feedback loop asymptotically stable.

In plain words

Write the coefficients of the polynomial in two rows, alternating: the first, third, fifth in the top row, and the second, fourth, sixth below. Make each new row from the two rows above it: for each position, cross-multiply the first column with the next column, take the difference, and divide by the first number of the row just above. Each new row is shorter than the one two rows above. Stop when there are n+1n + 1 rows. Then read down the first column and count how often the sign flips. That count is the number of roots with a positive real part. If a first entry is zero, the table needs one of two repairs, described below.

The problem

Given a real polynomial p(s)=a0sn+a1sn−1+⋯+anp(s) = a_0 s^n + a_1 s^{n-1} + \dots + a_n with a0≠0a_0 \ne 0, written with the highest power first, count its roots in the open right half plane {Re⁡s>0}\{\operatorname{Re} s > 0\}, counted with multiplicity, and decide whether all roots lie in the open left half plane. The usual source of pp is the characteristic polynomial det⁡(sI−A)\det(sI - A) of a linear system, or the denominator of a closed-loop transfer function.

Notation. Row ii belongs to the power sn−is^{n-i}, for i=0,…,ni = 0, \dots, n, and has ⌊(n−i)/2⌋+1\lfloor (n - i)/2 \rfloor + 1 entries ri,0,ri,1,…r_{i,0}, r_{i,1}, \dots. The first column is ri=ri,0r_i = r_{i,0}. An entry outside a row counts as 00. VV is the number of sign changes in r0,r1,…,rnr_0, r_1, \dots, r_n, and N(p)N(p) and Z(p)Z(p) are the numbers of roots of pp in the open right half plane and on the imaginary axis.

The algorithm

  1. ROUTH-ARRAY(a_0, ..., a_n)
  2. 1remove zero leading coefficients; if no coefficient is left then error
  3. 2row_0 ← (a_0, a_2, a_4, ...); row_1 ← (a_1, a_3, a_5, ...) ▷ pad row_1 with 0 to length ⌊(n-1)/2⌋ + 1
  4. 3for i ← 1 to n do
  5. 4if i ≥ 2 then
  6. 5c ← row_{i-1}[0]
  7. 6for j ← 0 to ⌊(n-i)/2⌋ do row_i[j] ← (c · row_{i-2}[j+1] - row_{i-2}[0] · row_{i-1}[j+1]) / c
  8. 7if every entry of row_i is 0 then ▷ zero row
  9. 8d ← n - i + 1; A(s) ← Σ_j row_{i-1}[j] · s^(d-2j) ▷ auxiliary polynomial
  10. 9row_i[j] ← (d - 2j) · row_{i-1}[j] for every j ▷ the coefficients of A'(s)
  11. 10else if row_i[0] = 0 then ▷ zero first entry
  12. 11row_i[0] ← ε ▷ ε is a positive infinitesimal
  13. 12V ← number of sign changes in row_0[0], ..., row_n[0], each sign taken as ε → 0+
  14. 13return the rows, V, and the list of the special cases met

Line L2 splits the coefficients by parity. Line L6 is the cross product rule: for rows (u0,u1,… )(u_0, u_1, \dots) and (c0,c1,… )(c_0, c_1, \dots) the next row is ((c0u1−u0c1)/c0,(c0u2−u0c2)/c0,… )((c_0 u_1 - u_0 c_1)/c_0, (c_0 u_2 - u_0 c_2)/c_0, \dots). Lines L7 to L9 handle a row of zeros: the row above defines an even or odd auxiliary polynomial AA of degree dd, and the zero row is replaced by the coefficients of its derivative. Lines L10 and L11 handle a zero first entry in a row that is not all zero: it is replaced by a small positive number ε\varepsilon, the later entries become rational functions of ε\varepsilon, and line L12 uses their signs for small ε>0\varepsilon > 0. A row may be multiplied by a positive number at any point without changing VV, which keeps hand calculations small.

The implementation computes in exact rational arithmetic, and it converts floating point input exactly. It keeps an entry that depends on ε\varepsilon as a quotient of two polynomials in ε\varepsilon; the sign as ε→0+\varepsilon \to 0+ is the sign of the quotient of the lowest nonzero coefficients. It also returns the list of special cases with the auxiliary polynomials, and is_hurwitz(p), which is true exactly when no special case occurs and V=0V = 0.

Example

The regular case. For p(s)=s3+s2+2s+8p(s) = s^3 + s^2 + 2s + 8:

row power entries
0 s3s^3 11, 22
1 s2s^2 11, 88
2 s1s^1 (1⋅2−1⋅8)/1=−6(1 \cdot 2 - 1 \cdot 8)/1 = -6
3 s0s^0 (−6⋅8−1⋅0)/(−6)=8(-6 \cdot 8 - 1 \cdot 0)/(-6) = 8

The first column 1,1,−6,81, 1, -6, 8 has two sign changes, so pp has two roots in the right half plane. Indeed p(s)=(s+2)(s2−s+4)p(s) = (s + 2)(s^2 - s + 4), with the roots −2-2 and 0.5±1.93649i0.5 \pm 1.93649 i. All coefficients of pp are positive, so the coefficient signs alone would not show this.

A gain range. For p(s)=s3+3s2+2s+Kp(s) = s^3 + 3 s^2 + 2 s + K the rows are (1,2)(1, 2), (3,K)(3, K), ((6−K)/3)((6 - K)/3) and (K)(K). The first column is positive exactly when 0<K<60 < K < 6, so the companion matrix of pp is Hurwitz for exactly these gains. For K=8K = 8 it is 1,3,−2/3,81, 3, -2/3, 8, with two sign changes.

A zero row. At K=6K = 6, row 2 is (6−6)/3=0(6 - 6)/3 = 0. The row above gives A(s)=3s2+6A(s) = 3 s^2 + 6, and row 2 becomes the coefficient of A′(s)=6sA'(s) = 6 s. Then row 3 is (6⋅6−3⋅0)/6=6(6 \cdot 6 - 3 \cdot 0)/6 = 6. The first column 1,3,6,61, 3, 6, 6 has no sign change, so no root lies in the right half plane. The roots of AA are ±i2\pm i \sqrt 2, and they are roots of pp: p(s)=(s+3)(s2+2)p(s) = (s + 3)(s^2 + 2). So pp has one root in the left half plane and two on the axis, and it is not Hurwitz, although V=0V = 0.

A zero first entry. For p(s)=s5+2s4+2s3+4s2+11s+10p(s) = s^5 + 2 s^4 + 2 s^3 + 4 s^2 + 11 s + 10:

row power entries
0 s5s^5 11, 22, 1111
1 s4s^4 22, 44, 1010
2 s3s^3 0→ε0 \to \varepsilon, 66
3 s2s^2 (4ε−12)/ε(4 \varepsilon - 12)/\varepsilon, 1010
4 s1s^1 6−10ε2/(4ε−12)→66 - 10 \varepsilon^2 / (4 \varepsilon - 12) \to 6
5 s0s^0 1010

For small ε>0\varepsilon > 0 the signs are +,+,+,−,+,++, +, +, -, +, +, so V=2V = 2. The roots are −1.30871-1.30871, −1.24066±1.0375i-1.24066 \pm 1.0375 i and 0.89502±1.4561i0.89502 \pm 1.4561 i: two in the right half plane.

Correctness

The proofs are in the correctness proof. They follow the degree reduction of Meinsma (1995).

  • Regular case (proved). If no special case occurs, pp has no root on the imaginary axis and N(p)=VN(p) = V.
  • Zero rows only (proved). If zero rows occur and no zero first entry does, then N(p)=VN(p) = V. The roots of pp on the imaginary axis are exactly those of the first auxiliary polynomial A1A_1, with multiplicity, and pp has n−V−Z(A1)n - V - Z(A_1) roots in the open left half plane.
  • One zero first entry (proved). If exactly one ε\varepsilon substitution and no zero row occur, and pp has no root on the imaginary axis, then N(p)=VN(p) = V. With several substitutions the implementation reuses the same ε\varepsilon; the count was correct on all the random tests, but this case is not proved.
  • Roots on the axis with ε\varepsilon (counterexample). If pp has roots on the imaginary axis and an ε\varepsilon substitution occurs, VV can be larger than N(p)N(p). See Pitfalls.
  • The Hurwitz decision (proved). is_hurwitz(p) is true if and only if all roots of pp have negative real part. A Hurwitz polynomial never produces a special case.
  • Hurwitz determinants (proved). In the regular case the leading principal minors of the Hurwitz matrix of pp are Δk=r1r2⋯rk\Delta_k = r_1 r_2 \cdots r_k.
  • Termination (proved). The loop runs nn times, and each row is computed once.

The tests compare the count with roots computed numerically by the Durand-Kerner method. They use more than 1000 random polynomials of degree up to 6 with integer coefficients from −3-3 to 33 and no root within 10−610^{-6} of the axis, more than 50 of which need the ε\varepsilon method, and more than 300 random polynomials whose table has a zero row.

Proof: The sign changes of the Routh array count the right half plane roots, in the regular case, with zero rows, and with one epsilon substitution when no root is on the axisfull

Let p(s)=a0sn+a1sn−1+⋯+anp(s) = a_0 s^n + a_1 s^{n-1} + \dots + a_n be real with a0≠0a_0 \ne 0 and n≥1n \ge 1. For a real polynomial gg, N(g)N(g) is the number of its roots in the open right half plane and Z(g)Z(g) the number on the imaginary axis, both counted with multiplicity. [ ⋅ ][\,\cdot\,] is 11 if the condition holds and 00 otherwise. A polynomial is even if it has only even powers and odd if it has only odd powers; such a polynomial has a parity. For gg with a parity, g(−s)=±g(s)g(-s) = \pm g(s), so its roots are symmetric about the origin. The arithmetic is exact. The proof follows the continuity argument of Meinsma (1995).

Rows as polynomials

Row ii of the array, with entries ri,0,ri,1,…r_{i,0}, r_{i,1}, \dots, stands for the polynomial

Ri(s)=ri,0 sn−i+ri,1 sn−i−2+ri,2 sn−i−4+⋯ ,R_i(s) = r_{i,0}\, s^{n-i} + r_{i,1}\, s^{n-i-2} + r_{i,2}\, s^{n-i-4} + \cdots ,

which has the parity of n−in - i. So R0R_0 and R1R_1 are the parts of pp with the parity of nn and of n−1n - 1, and p=R0+R1p = R_0 + R_1. Write ri=ri,0r_i = r_{i,0} and, when ri≠0r_i \ne 0, Pi=Ri+Ri+1P_i = R_i + R_{i+1}, a polynomial of degree n−in - i whose two parts are RiR_i and Ri+1R_{i+1} (Rn+1=0R_{n+1} = 0).

Lemma 0 (the cross product rule). If ri−1≠0r_{i-1} \ne 0 and ri≠0r_i \ne 0, line L6 computes

Ri+1=Ri−1−η s Ri,η=ri−1/ri.R_{i+1} = R_{i-1} - \eta\, s\, R_i , \qquad \eta = r_{i-1} / r_i .

Proof. With $u = $ row i−1i - 1 and $c = $ row ii, the coefficient of sn−i−1−2js^{n-i-1-2j} in Ri−1R_{i-1} is uj+1u_{j+1}, and in sRis R_i it is cj+1c_{j+1}. The coefficient of sn−i+1s^{n-i+1} is u0−ηc0=0u_0 - \eta c_0 = 0. So Ri−1−ηsRi=∑j(uj+1−u0cj+1/c0) sn−i−1−2jR_{i-1} - \eta s R_i = \sum_j (u_{j+1} - u_0 c_{j+1} / c_0)\, s^{n-i-1-2j}, and uj+1−u0cj+1/c0=(c0uj+1−u0cj+1)/c0u_{j+1} - u_0 c_{j+1}/c_0 = (c_0 u_{j+1} - u_0 c_{j+1})/c_0 is line L6. □\square

Two facts about roots

Fact 1 (continuity of roots). Let gtg_t be real polynomials whose coefficients depend continuously on tt in an interval JJ, with constant degree kk. If no gtg_t, t∈Jt \in J, has a root on the imaginary axis, then N(gt)N(g_t) is constant on JJ. Reason. By Rouché's theorem, for tt near t0t_0 the roots of gtg_t lie in small discs around the roots of gt0g_{t_0}, each disc holding as many roots as the multiplicity of its center. Discs that do not meet the axis keep the count on each side, so N(gt)N(g_t) is locally constant, and JJ is connected.

Fact 2 (a root to infinity). If moreover J=[t0,1)J = [t_0, 1), gt→g1g_t \to g_1 coefficientwise, the leading coefficient of gtg_t tends to 00, and g1g_1 has degree k−1k - 1, then for tt close to 11, k−1k - 1 roots of gtg_t lie in small discs around the roots of g1g_1 and the last root leaves every bounded set. Reason. Rouché's theorem on the discs around the roots of g1g_1 gives k−1k - 1 roots in the discs; on a bounded set outside the discs ∣gt∣|g_t| is bounded away from 00 for tt near 11, because gt→g1g_t \to g_1 uniformly there.

Lemma 1: the imaginary axis

Let FF and GG be real polynomials of opposite parity. Then for real ω\omega, F(iω)+G(iω)=0F(i\omega) + G(i\omega) = 0 if and only if F(iω)=0F(i\omega) = 0 and G(iω)=0G(i\omega) = 0.

Proof. An even real polynomial takes real values at iωi\omega, and an odd one takes purely imaginary values. So one of F(iω)F(i\omega), G(iω)G(i\omega) is the real part of the sum and the other is ii times its imaginary part. □\square

Now let FF and GG have opposite parity, and let D=gcd⁡(F,G)D = \gcd(F, G). Since F(−s)=±F(s)F(-s) = \pm F(s) and G(−s)=±G(s)G(-s) = \pm G(s), D(−s)D(-s) is also a common divisor of the same degree, so D(−s)=±D(s)D(-s) = \pm D(s), and DD has a parity. Then F/DF/D and G/DG/D have parities, opposite to each other, and they are coprime. By Lemma 1, F/D+G/DF/D + G/D has no root on the axis. Hence:

Corollary 1. If p=F+Gp = F + G with FF, GG of opposite parity and D=gcd⁡(F,G)D = \gcd(F, G), then the roots of pp on the imaginary axis are exactly the roots of DD on the axis, with the same multiplicities. In particular Z(p)=Z(D)Z(p) = Z(D).

Lemma 2: one step lowers the degree

Let p=F+Gp = F + G have degree m≥1m \ge 1, where FF has the parity of mm and the leading coefficient a0≠0a_0 \ne 0, and GG has the other parity and the coefficient a1≠0a_1 \ne 0 at sm−1s^{m-1}. Let η=a0/a1\eta = a_0 / a_1, H=F−ηsGH = F - \eta s G and q=G+Hq = G + H. Then:

(a) qq has degree m−1m - 1, its parts are GG (leading coefficient a1a_1) and HH, and gcd⁡(G,H)=gcd⁡(F,G)\gcd(G, H) = \gcd(F, G);

(b) Z(q)=Z(p)Z(q) = Z(p), with the same roots on the axis;

(c) N(p)=N(q)+[a0a1<0]N(p) = N(q) + [a_0 a_1 < 0].

Proof. (a) sGs G has the parity of mm and the leading term a1sma_1 s^m, so HH has the parity of mm and degree at most m−2m - 2. A common divisor of FF and GG divides HH, and a common divisor of GG and HH divides F=H+ηsGF = H + \eta s G.

(b) Corollary 1 for pp and for qq, with the same DD.

(c) Let D=gcd⁡(F,G)D = \gcd(F, G), F~=F/D\tilde F = F/D, G~=G/D\tilde G = G/D, and for t∈[0,1]t \in [0, 1]

pt=F+G−tηsG=D⋅p~t,p~t=(F~−tηsG~)+G~.p_t = F + G - t \eta s G = D \cdot \tilde p_t , \qquad \tilde p_t = (\tilde F - t \eta s \tilde G) + \tilde G .

Then p0=pp_0 = p and p1=qp_1 = q. The polynomial F~−tηsG~\tilde F - t\eta s \tilde G has the parity of F~\tilde F, and gcd⁡(F~−tηsG~,G~)=gcd⁡(F~,G~)=1\gcd(\tilde F - t\eta s\tilde G, \tilde G) = \gcd(\tilde F, \tilde G) = 1. By Lemma 1, no p~t\tilde p_t has a root on the axis. The coefficient of sms^m in ptp_t is a0−tηa1=(1−t)a0a_0 - t \eta a_1 = (1 - t) a_0, which is nonzero for t<1t < 1; the coefficient of sm−1s^{m-1} is a1a_1 for every tt, because FF and sGs G contribute nothing to that power. So p~t\tilde p_t has constant degree k=m−deg⁡Dk = m - \deg D on [0,1)[0, 1), and p~1=q/D\tilde p_1 = q / D has degree k−1k - 1.

By Fact 1, N(p~t)=N(p~0)N(\tilde p_t) = N(\tilde p_0) for t∈[0,1)t \in [0, 1). By Fact 2, for tt near 11, k−1k - 1 roots of p~t\tilde p_t lie near the roots of p~1\tilde p_1, which are off the axis, so they contribute N(p~1)N(\tilde p_1); the last root ρ(t)\rho(t) leaves every bounded set. The sum of all roots of ptp_t is −a1/((1−t)a0)-a_1 / ((1 - t) a_0). The roots of DD do not move and the other k−1k - 1 roots of p~t\tilde p_t stay bounded, so ρ(t)=−a1/((1−t)a0)+O(1)\rho(t) = -a_1 / ((1 - t) a_0) + O(1), whose real part tends to +∞+\infty if a0a1<0a_0 a_1 < 0 and to −∞-\infty if a0a1>0a_0 a_1 > 0. So N(p~0)=N(p~1)+[a0a1<0]N(\tilde p_0) = N(\tilde p_1) + [a_0 a_1 < 0], and adding N(D)N(D) on both sides gives (c). □\square

By Lemma 0, when ri≠0r_i \ne 0 and ri+1≠0r_{i+1} \ne 0, Lemma 2 applied to PiP_i (with F=RiF = R_i, G=Ri+1G = R_{i+1}) gives q=Pi+1q = P_{i+1}. So the array is the sequence P0=p,P1,P2,…P_0 = p, P_1, P_2, \dots of Lemma 2.

Theorem 1: the regular case

If no special case occurs, then Z(p)=0Z(p) = 0 and N(p)=VN(p) = V, the number of sign changes in r0,…,rnr_0, \dots, r_n.

Proof. All rir_i are nonzero. For i=0,…,n−1i = 0, \dots, n - 1, Lemma 2 gives N(Pi)=N(Pi+1)+[riri+1<0]N(P_i) = N(P_{i+1}) + [r_i r_{i+1} < 0] and Z(Pi)=Z(Pi+1)Z(P_i) = Z(P_{i+1}). Pn=rnP_n = r_n is a nonzero constant, with N=Z=0N = Z = 0. Adding up, N(p)=∑i[riri+1<0]=VN(p) = \sum_i [r_i r_{i+1} < 0] = V and Z(p)=0Z(p) = 0. ■\blacksquare

Lemma 3: the derivative of an even or odd polynomial

Let AA be even or odd, of degree d≥1d \ge 1. Then A+A′A + A' has degree dd, its parts are AA and A′A', N(A+A′)=N(A)N(A + A') = N(A), and the roots of A+A′A + A' on the axis are the multiple roots of AA on the axis, each with its multiplicity lowered by one.

Proof. A′A' has the other parity and degree d−1d - 1. Let At=A+tA′A_t = A + t A' for t∈[0,1]t \in [0, 1]; its degree is dd for every tt. For t>0t > 0, Lemma 1 says At(iω)=0A_t(i\omega) = 0 if and only if A(iω)=A′(iω)=0A(i\omega) = A'(i\omega) = 0. Let iωi\omega be a root of AA of multiplicity μ\mu and write A=(s−iω)μhA = (s - i\omega)^\mu h with h(iω)≠0h(i\omega) \ne 0. Then

At=(s−iω)μ−1(tμh+(s−iω)(h+th′)),A_t = (s - i\omega)^{\mu - 1} \bigl(t \mu h + (s - i\omega)(h + t h')\bigr) ,

and the bracket equals tμh(iω)≠0t \mu h(i\omega) \ne 0 at s=iωs = i\omega, so for t>0t > 0 the multiplicity of iωi\omega in AtA_t is exactly μ−1\mu - 1. Let EE be the product of (s−iω)μ−1(s - i\omega)^{\mu - 1} over the distinct roots iωi\omega of AA on the axis. Conjugate roots have equal multiplicities, so EE is real. EE divides every AtA_t, and Bt=At/EB_t = A_t / E has no root on the axis for t∈(0,1]t \in (0, 1], so by Fact 1 N(Bt)N(B_t) is constant on (0,1](0, 1].

As t→0+t \to 0+, Bt→B0=A/EB_t \to B_0 = A / E, which has the same degree, a simple root at each axis root iωi\omega of AA, and the roots of AA off the axis. Near a simple root iωi\omega of B0B_0, the implicit function theorem gives a root s(t)=iω+t s′(0)+O(t2)s(t) = i\omega + t\, s'(0) + O(t^2) of BtB_t with s′(0)=−∂tBt/∂sB0s'(0) = -\partial_t B_t / \partial_s B_0 at (0,iω)(0, i\omega). With E=(s−iω)μ−1eE = (s - i\omega)^{\mu-1} e, e(iω)≠0e(i\omega) \ne 0, one finds ∂sB0(iω)=h(iω)/e(iω)\partial_s B_0(i\omega) = h(i\omega)/e(i\omega) and ∂tBt(iω)=(A′/E)(iω)=μh(iω)/e(iω)\partial_t B_t (i\omega) = (A'/E)(i\omega) = \mu h(i\omega)/e(i\omega). So s′(0)=−μs'(0) = -\mu, and s(t)s(t) lies in the open left half plane for small t>0t > 0. The roots of B0B_0 off the axis keep their side for small tt. Hence N(Bt)=N(B0)=N(A)N(B_t) = N(B_0) = N(A) for small t>0t > 0, and so for t=1t = 1: N(A+A′)=N(E)+N(B1)=0+N(A)N(A + A') = N(E) + N(B_1) = 0 + N(A). □\square

Since the roots of AA are symmetric about the origin, AA has as many roots in the left as in the right half plane, so d=2N(A)+Z(A)d = 2 N(A) + Z(A).

Theorem 2: zero rows

Suppose zero rows occur and no zero first entry does. Let A1A_1 be the auxiliary polynomial of the first zero row. Then N(p)=VN(p) = V, the roots of pp on the imaginary axis are those of A1A_1 with multiplicity, and pp has n−V−Z(A1)n - V - Z(A_1) roots in the open left half plane.

Proof. Every row, after lines L7 to L11, has a nonzero first entry: a regular row by assumption, and a replaced zero row because its first entry is dd times the nonzero first entry of the row above. So c≠0c \ne 0 in line L5 throughout.

Induction on the number zz of zero rows; z=0z = 0 is Theorem 1. Let z≥1z \ge 1 and let row k≥1k \ge 1 be the first zero row, so Rk=0R_k = 0 before the replacement and Pk−1=Rk−1=A1P_{k-1} = R_{k-1} = A_1, of degree d=n−k+1d = n - k + 1. Lemma 2 for i=0,…,k−2i = 0, \dots, k - 2 gives

N(p)=V(r0,…,rk−1)+N(A1)N(p) = V(r_0, \dots, r_{k-1}) + N(A_1)

and the same roots on the axis for pp and A1A_1. (For k=1k = 1, p=A1p = A_1.) After the replacement, row k−1k - 1 holds the coefficients of A1A_1 and row kk those of A1′A_1', and every later row depends only on these two rows. So rows k−1,…,nk - 1, \dots, n are the array of A1+A1′A_1 + A_1', whose parts are A1A_1 and A1′A_1'; it has z−1z - 1 zero rows and no zero first entry. By induction and Lemma 3, V(rk−1,…,rn)=N(A1+A1′)=N(A1)V(r_{k-1}, \dots, r_n) = N(A_1 + A_1') = N(A_1). Adding the two counts, V=N(p)V = N(p). The left half plane count is n−N(p)−Z(p)n - N(p) - Z(p). ■\blacksquare

Theorem 3: one zero first entry

Suppose exactly one ε\varepsilon substitution occurs, in row kk, no zero row occurs, and pp has no root on the imaginary axis. Then N(p)=VN(p) = V, with the signs taken as ε→0+\varepsilon \to 0+.

Proof. Rows 0,…,k−10, \dots, k - 1 have nonzero first entries, so Lemma 2 for i=0,…,k−2i = 0, \dots, k - 2 gives N(p)=V(r0,…,rk−1)+N(Pk−1)N(p) = V(r_0, \dots, r_{k-1}) + N(P_{k-1}) and Z(Pk−1)=Z(p)=0Z(P_{k-1}) = Z(p) = 0. Here Pk−1=Rk−1+RkP_{k-1} = R_{k-1} + R_k, where Rk≠0R_k \ne 0 has a zero coefficient at sn−ks^{n-k}. For real ε\varepsilon let

Pε=Pk−1+ε sn−k,P^\varepsilon = P_{k-1} + \varepsilon\, s^{n-k} ,

whose parts are Rk−1R_{k-1} and Rk+εsn−kR_k + \varepsilon s^{n-k}. The rows k−1,…,nk - 1, \dots, n that the algorithm computes, with ε\varepsilon as a symbol, are rational functions of ε\varepsilon, and every first entry ri(ε)r_i(\varepsilon), i≥ki \ge k, is a nonzero rational function, since no further special case occurs. Only finitely many ε\varepsilon make a numerator or a denominator of some entry vanish. For every other real ε\varepsilon, evaluating the entries at ε\varepsilon gives the numerical array of PεP^\varepsilon, with the same operations and nonzero divisors, and that array is regular. A nonzero rational function has a constant sign on some interval (0,ε0)(0, \varepsilon_0), namely its sign as ε→0+\varepsilon \to 0+. So for small ε>0\varepsilon > 0, Theorem 1 gives N(Pε)=V(rk−1,rk(ε),…,rn(ε))N(P^\varepsilon) = V(r_{k-1}, r_k(\varepsilon), \dots, r_n(\varepsilon)), which is the count of line L12 on rows k−1,…,nk - 1, \dots, n.

As ε→0\varepsilon \to 0, Pε→Pk−1P^\varepsilon \to P_{k-1} with the constant degree n−k+1n - k + 1 and leading coefficient rk−1r_{k-1}, and Pk−1P_{k-1} has no root on the axis. By Fact 1 (on a small interval around 00, where no PεP^\varepsilon has a root on the axis, by continuity), N(Pε)=N(Pk−1)N(P^\varepsilon) = N(P_{k-1}) for small ε\varepsilon. Adding, N(p)=VN(p) = V. ■\blacksquare

What is not proved. If a second substitution occurs, the implementation uses the same ε\varepsilon, so the polynomial and the perturbation both depend on ε\varepsilon, and the argument above does not apply. The tests found no wrong count in that case for polynomials without roots near the axis. Combinations of ε\varepsilon and zero rows are also not covered here.

The hypothesis on the axis is needed. p(s)=s5+3s3+s2+2s+1=(s2+1)(s3+2s+1)p(s) = s^5 + 3 s^3 + s^2 + 2 s + 1 = (s^2 + 1)(s^3 + 2 s + 1) has a1=0a_1 = 0, so the substitution happens in row 1. The signs as ε→0+\varepsilon \to 0+ are +,+,−,+,−,++, +, -, +, -, +, so V=4V = 4, but N(p)=2N(p) = 2: the roots are ±i\pm i, −0.4534-0.4534 and 0.2267±1.46771i0.2267 \pm 1.46771 i. In the proof, Pε=p+εs4P^\varepsilon = p + \varepsilon s^4 moves both axis roots into the right half plane.

Theorem 4: the Hurwitz decision

is_hurwitz(p), which is true exactly when no special case occurs and V=0V = 0, is true if and only if every root of pp has a negative real part.

Proof. If no special case occurs and V=0V = 0, Theorem 1 gives N(p)=Z(p)=0N(p) = Z(p) = 0. Conversely, let pp be Hurwitz. Then p/a0p / a_0 is a product of factors s+ρs + \rho with ρ>0\rho > 0 and s2+2σs+σ2+τ2s^2 + 2\sigma s + \sigma^2 + \tau^2 with σ>0\sigma > 0, so all coefficients of pp are nonzero and have the sign of a0a_0; in particular a0a1>0a_0 a_1 > 0. Lemma 2 applies to P0=pP_0 = p and gives N(P1)=N(p)−0=0N(P_1) = N(p) - 0 = 0 and Z(P1)=Z(p)=0Z(P_1) = Z(p) = 0; P1P_1 has degree n−1n - 1, so it is Hurwitz. By induction every PiP_i is Hurwitz of degree n−in - i, so its first two coefficients rir_i and ri+1r_{i+1} are nonzero and of the same sign. Hence no row is zero, no first entry is zero, and V=0V = 0. ■\blacksquare

Theorem 5: the Hurwitz determinants

Let HH be the n×nn \times n Hurwitz matrix of pp, Hij=a2j−iH_{ij} = a_{2j - i} (with ak=0a_k = 0 for k<0k < 0 or k>nk > n), and Δk\Delta_k its leading principal minor of order kk. In the regular case, Δk=r1r2⋯rk\Delta_k = r_1 r_2 \cdots r_k for k=1,…,nk = 1, \dots, n.

Proof. Induction on nn. Row 2l−12l - 1 of HH is (0,…,0,a1,a3,… )(0, \dots, 0, a_1, a_3, \dots) and row 2l2l is (0,…,0,a0,a2,… )(0, \dots, 0, a_0, a_2, \dots), both starting in column ll. Subtract η=a0/a1\eta = a_0 / a_1 times row 2l−12l - 1 from row 2l2l, for each ll. This adds multiples of earlier rows to later rows, so it does not change any leading principal minor. Row 2l2l becomes (0,…,0,0,a2−ηa3,a4−ηa5,… )(0, \dots, 0, 0, a_2 - \eta a_3, a_4 - \eta a_5, \dots), which is the row of R2R_2 starting in column l+1l + 1. Now column 1 is (a1,0,…,0)T(a_1, 0, \dots, 0)^T, and the matrix left after deleting row 1 and column 1 is the Hurwitz matrix of P1=R1+R2P_1 = R_1 + R_2, of degree n−1n - 1, whose coefficients are a1,r2,0,a3,r2,1,…a_1, r_{2,0}, a_3, r_{2,1}, \dots. So Δk(p)=a1 Δk−1(P1)\Delta_k(p) = a_1\, \Delta_{k-1}(P_1), with Δ0=1\Delta_0 = 1. The array of P1P_1 is rows 1,…,n1, \dots, n of the array of pp, so by induction Δk−1(P1)=r2⋯rk\Delta_{k-1}(P_1) = r_2 \cdots r_k, and a1=r1a_1 = r_1. ■\blacksquare

With a0>0a_0 > 0, a positive first column is thus the same as Δ1,…,Δn>0\Delta_1, \dots, \Delta_n > 0, which is Hurwitz's form of the criterion.

Termination and cost

The loop in line L3 runs nn times. Row ii has ⌊(n−i)/2⌋+1\lfloor (n - i)/2 \rfloor + 1 entries, each computed once by line L6 with two multiplications, a subtraction and a division, and lines L7 to L11 cost O(n)O(n) per row. So the algorithm stops after O(n2)O(n^2) arithmetic operations on the entries, which are numbers in the regular case and with zero rows, and rational functions of ε\varepsilon after a substitution.

Complexity

  • Time. Row ii has ⌊(n−i)/2⌋+1\lfloor (n - i)/2 \rfloor + 1 entries, each made by two multiplications, one subtraction and one division. In all that is about n2/4n^2/4 cross products, O(n2)O(n^2) arithmetic operations. A zero row costs O(n)O(n) more.
  • Space. O(n2)O(n^2) numbers for the whole table, or O(n)O(n) if only the last two rows and the first column are kept.
  • Exact arithmetic. The numbers in the table are rational functions of the coefficients, and their size can grow with nn. With symbolic coefficients, such as a gain KK, the entries are rational functions of KK, and the conditions ri>0r_i > 0 become polynomial inequalities in KK.
  • The ε\varepsilon case. The entries become rational functions of ε\varepsilon whose degree can grow with each row, so the cost of that case is higher than O(n2)O(n^2) operations on numbers.

Properties

  • Exact. In rational arithmetic the count is a proof, not an estimate.
  • No roots computed. Only coefficient arithmetic, and no evaluation of pp.
  • Symbolic. The table can be built with unknown parameters, which gives the parameter region in which pp is Hurwitz.
  • Scaling. Multiplying a row by a positive number, or pp by a nonzero number, does not change VV.
  • Same as Gaussian elimination. The table is the elimination of the Hurwitz matrix of pp without pivoting, which is why Δk=r1⋯rk\Delta_k = r_1 \cdots r_k (see Gaussian elimination). It is also a form of the Euclidean algorithm on the even and odd parts of pp, and the rows with polynomial meaning form a sequence of the Sturm kind.

Variants and improvements

  • Hurwitz determinants. The conditions Δ1>0,…,Δn>0\Delta_1 > 0, \dots, \Delta_n > 0 (for a0>0a_0 > 0) are equivalent to a positive first column. They are easier to state with symbols and harder to compute; see Routh-Hurwitz criterion.
  • Liénard-Chipart test. If all coefficients are positive, only every second Hurwitz determinant needs to be checked (Gantmacher, Chapter XV).
  • Relative stability. To test whether all roots satisfy Re⁡s<−σ\operatorname{Re} s < -\sigma, build the table for p(s−σ)p(s - \sigma).
  • Discrete time. For roots inside the unit circle use the Jury stability test or the Schur-Cohn test, or apply the bilinear transform and then the Routh array.
  • Families of polynomials. For coefficients that vary in intervals, Kharitonov's theorem reduces the question to four Routh tests, and the edge theorem treats polytopes of polynomials.
  • Other ways around zero entries. Instead of ε\varepsilon, one can apply the table to p(s)(s+1)p(s) (s + 1) or to the reversed polynomial snp(1/s)s^n p(1/s), which have the same number of right half plane roots and may avoid the zero.

When to use it

Use the Routh array for polynomials of small degree, for hand calculations, and above all when the coefficients contain parameters: the range of a gain KK for which a loop is asymptotically stable comes straight from the first column, and it matches the crossing points of the root locus with the imaginary axis. For a numerical matrix of high order it is better not to form the characteristic polynomial at all, because its roots can be very sensitive to its coefficients (see root conditioning). Compute the eigenvalues of the matrix, or use the Lyapunov theorem for linear systems, instead.

Pitfalls

  • Zero tests in floating point. In floating point a first entry that should be zero comes out as a tiny number of either sign, and the count can be wrong. A tiny entry means that some root is close to the imaginary axis. The implementation computes exactly to avoid this.
  • No sign change is not enough. V=0V = 0 means no root in the right half plane; it does not exclude roots on the axis. The example at K=6K = 6 has V=0V = 0 and roots ±i2\pm i \sqrt 2. The polynomial is Hurwitz only if no special case occurs and V=0V = 0.
  • The ε\varepsilon method with roots on the axis. For p(s)=s5+3s3+s2+2s+1=(s2+1)(s3+2s+1)p(s) = s^5 + 3 s^3 + s^2 + 2 s + 1 = (s^2 + 1)(s^3 + 2 s + 1), row 1 starts with 00, the ε\varepsilon method gives the signs +,+,−,+,−,++, +, -, +, -, + and V=4V = 4, but pp has only two roots in the right half plane, 0.2267±1.46771i0.2267 \pm 1.46771 i. The roots ±i\pm i on the axis are counted as if they were in the right half plane. When ε\varepsilon is needed, check for roots on the axis, for example with the greatest common divisor of the even and odd parts (see polynomial GCD).
  • Rows multiplied by a negative number. Only positive factors are allowed; a negative factor changes the signs.
  • A missing coefficient. A zero or negative coefficient already shows that pp is not Hurwitz (for a0>0a_0 > 0). The table is still needed to count the right half plane roots.
  • Leading zeros. A zero leading coefficient changes the degree; the implementation removes it, and it rejects the zero polynomial.

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()
routh_array.py 285 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/routh-array/. The authors are listed in prov/43YJD3.jsonl.

"""The Routh array of a real polynomial, in exact arithmetic.

A polynomial is a list of coefficients, highest power first:
[a0, a1, ..., an] is a0 s^n + a1 s^(n-1) + ... + an. The entries may be
int, Fraction or float; floats are converted exactly to Fraction.

Two special cases are handled as on the page:
- a zero first entry in a row that is not all zero is replaced by a
  positive infinitesimal eps (the epsilon method). The entries are then
  rational functions of eps, and a sign is the sign as eps -> 0+;
- a row of zeros is replaced by the coefficients of the derivative of the
  auxiliary polynomial, which is made from the row above.
"""

from fractions import Fraction


# ---------------------------------------------------------------- eps algebra
# A polynomial in eps is a list of Fractions, lowest power first, with no
# trailing zeros. The zero polynomial is [].


def _ptrim(a):
    a = list(a)
    while a and a[-1] == 0:
        a.pop()
    return a


def _padd(a, b):
    n = max(len(a), len(b))
    return _ptrim([(a[i] if i < len(a) else 0) + (b[i] if i < len(b) else 0) for i in range(n)])


def _pneg(a):
    return [-x for x in a]


def _pmul(a, b):
    if not a or not b:
        return []
    c = [Fraction(0)] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        if x:
            for j, y in enumerate(b):
                c[i + j] += x * y
    return _ptrim(c)


def _pdivmod(a, b):
    """Quotient and remainder of a by b (b nonzero), lowest power first."""
    a = list(a)
    q = [Fraction(0)] * max(len(a) - len(b) + 1, 0)
    lb = b[-1]
    while len(a) >= len(b) and a:
        k = len(a) - len(b)
        f = a[-1] / lb
        q[k] = f
        for i, y in enumerate(b):
            a[i + k] -= f * y
        a = _ptrim(a)
    return _ptrim(q), a


def _pgcd(a, b):
    while b:
        a, b = b, _pdivmod(a, b)[1]
    return [x / a[-1] for x in a]  # monic


def _lowest(a):
    for x in a:
        if x != 0:
            return x
    return Fraction(0)


class EpsFrac:
    """A rational function num(eps) / den(eps), eps a positive infinitesimal."""

    __slots__ = ("num", "den")

    def __init__(self, num, den=None):
        num = _ptrim(Fraction(x) for x in num)
        den = [Fraction(1)] if den is None else _ptrim(Fraction(x) for x in den)
        if not den:
            raise ZeroDivisionError("zero denominator")
        if not num:
            self.num, self.den = [], [Fraction(1)]
            return
        if len(den) > 1:
            g = _pgcd(num, den)
            if len(g) > 1:
                num = _pdivmod(num, g)[0]
                den = _pdivmod(den, g)[0]
        lead = den[-1]
        self.num = [x / lead for x in num]
        self.den = [x / lead for x in den]

    @staticmethod
    def const(x):
        return EpsFrac([x])

    @staticmethod
    def eps():
        return EpsFrac([0, 1])

    def is_zero(self):
        return not self.num

    def is_constant(self):
        return len(self.num) <= 1 and len(self.den) == 1

    def value(self):
        """The Fraction value; only for a constant."""
        if not self.is_constant():
            raise ValueError("entry depends on eps")
        return self.num[0] if self.num else Fraction(0)

    def sign(self):
        """The sign as eps -> 0+: -1, 0 or +1."""
        if not self.num:
            return 0
        s = _lowest(self.num) * _lowest(self.den)
        return 1 if s > 0 else -1

    def __sub__(self, o):
        return EpsFrac(_padd(_pmul(self.num, o.den), _pneg(_pmul(o.num, self.den))), _pmul(self.den, o.den))

    def __mul__(self, o):
        return EpsFrac(_pmul(self.num, o.num), _pmul(self.den, o.den))

    def __truediv__(self, o):
        if o.is_zero():
            raise ZeroDivisionError("division by a zero entry")
        return EpsFrac(_pmul(self.num, o.den), _pmul(self.den, o.num))

    def __repr__(self):
        if self.is_constant():
            return repr(self.value())
        return "EpsFrac(%r, %r)" % (self.num, self.den)


# ---------------------------------------------------------------- the array


class RouthResult:
    """rows: the array, row i belongs to s^(n-i); entries are EpsFrac.
    first_column: the first entries; a Fraction where it does not depend on eps.
    signs: the signs of the first column (as eps -> 0+).
    sign_changes: the number of sign changes in signs.
    events: a list of ("epsilon", i) and ("zero_row", i, aux) in the order met;
    aux is the auxiliary polynomial (highest power first) made from row i - 1.
    """

    def __init__(self, degree, rows, events):
        self.degree = degree
        self.rows = rows
        self.events = events
        self.signs = [r[0].sign() for r in rows]
        self.first_column = [_out(r[0]) for r in rows]
        self.sign_changes = sum(1 for a, b in zip(self.signs, self.signs[1:]) if a != b)  # @line L12

    @property
    def regular(self):
        return not self.events

    @property
    def used_epsilon(self):
        return any(e[0] == "epsilon" for e in self.events)

    def table(self):
        """The rows as lists of plain values (Fraction where possible)."""
        return [[_out(x) for x in r] for r in self.rows]


def _out(x):
    return x.value() if x.is_constant() else x


def normalize(coeffs):
    """Exact Fraction coefficients without leading zeros."""
    c = [Fraction(x) for x in coeffs]
    while c and c[0] == 0:
        c.pop(0)
    if not c:
        raise ValueError("the zero polynomial has no Routh array")
    return c


def routh_array(coeffs):
    """Build the Routh array of the polynomial coeffs (highest power first)."""
    a = normalize(coeffs)  # @line L1
    n = len(a) - 1
    width = n // 2 + 1

    def row_len(i):
        return (n - i) // 2 + 1

    rows = [[EpsFrac.const(x) for x in a[0::2]], [EpsFrac.const(x) for x in a[1::2]]]  # @line L2
    rows = [r + [EpsFrac.const(0)] * (row_len(i) - len(r)) for i, r in enumerate(rows[: n + 1])]
    events = []
    zero = EpsFrac.const(0)

    i = 1
    while i <= n:  # @line L3
        if i >= 2:  # @line L4
            up, cur = rows[i - 2], rows[i - 1]
            c = cur[0]  # @line L5
            new = []
            for j in range(row_len(i)):
                u1 = up[j + 1] if j + 1 < len(up) else zero
                c1 = cur[j + 1] if j + 1 < len(cur) else zero
                new.append((c * u1 - up[0] * c1) / c)  # @line L6
            rows.append(new)
        row = rows[i]
        if all(x.is_zero() for x in row):  # @line L7
            # Row of zeros: use the derivative of the auxiliary polynomial.
            prev = rows[i - 1]
            d = n - (i - 1)  # @line L8
            aux = []
            for j, x in enumerate(prev):
                aux.append(_out(x))
                if j < len(prev) - 1:
                    aux.append(Fraction(0))
            aux = (aux + [Fraction(0)] * (d + 1))[: d + 1]
            rows[i] = [EpsFrac.const(d - 2 * j) * prev[j] for j in range(row_len(i))]  # @line L9
            events.append(("zero_row", i, aux))
        elif rows[i][0].is_zero():  # @line L10
            rows[i][0] = EpsFrac.eps()  # @line L11
            events.append(("epsilon", i))
        i += 1
    assert len(rows) == n + 1 and all(len(r) <= width for r in rows)
    return RouthResult(n, rows, events)  # @line L13


def rhp_count(coeffs):
    """The number of sign changes in the first column. It equals the number
    of roots in the open right half plane in the cases proved on the page."""
    return routh_array(coeffs).sign_changes


def is_hurwitz(coeffs):
    """True if and only if every root has a negative real part."""
    r = routh_array(coeffs)
    return r.regular and r.sign_changes == 0


def hurwitz_determinants(coeffs):
    """The leading principal minors D_1, ..., D_n of the Hurwitz matrix,
    computed directly by fraction elimination (used to check the page)."""
    a = normalize(coeffs)
    n = len(a) - 1

    def coef(k):
        return a[k] if 0 <= k <= n else Fraction(0)

    H = [[coef(2 * (j + 1) - (i + 1)) for j in range(n)] for i in range(n)]
    out = []
    for k in range(1, n + 1):
        out.append(_det([row[:k] for row in H[:k]]))
    return out


def _det(M):
    M = [list(r) for r in M]
    n = len(M)
    det = Fraction(1)
    for c in range(n):
        p = next((r for r in range(c, n) if M[r][c] != 0), None)
        if p is None:
            return Fraction(0)
        if p != c:
            M[c], M[p] = M[p], M[c]
            det = -det
        det *= M[c][c]
        for r in range(c + 1, n):
            f = M[r][c] / M[c][c]
            if f:
                for k in range(c, n):
                    M[r][k] -= f * M[c][k]
    return det
test_routh_array.py 203 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/routh-array/. The authors are listed in prov/43YJD3.jsonl.

import random
from fractions import Fraction

import ctlmat as cm
from routh_array import EpsFrac, hurwitz_determinants, is_hurwitz, rhp_count, routh_array

# Root counts from floating point roots. A root with |Re| below AXIS is
# taken to lie on the imaginary axis. polyroots is accurate to about 1e-8
# for double roots and 1e-5 for triple roots, so AXIS = 1e-3 is safe for the
# small integer polynomials used here.
AXIS = 1e-3


def real_parts(c):
    return [z.real for z in cm.polyroots(c)]


def rhp_true(c):
    return sum(1 for x in real_parts(c) if x > AXIS)


def random_poly(rng, lo=-3, hi=3, max_degree=6):
    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 test_check_value():
    r = routh_array([1, 1, 2, 8])
    assert r.first_column == [1, 1, -6, 8]
    assert r.regular and r.sign_changes == 2
    assert rhp_count([1, 1, 2, 8]) == 2 == rhp_true([1, 1, 2, 8])
    assert not is_hurwitz([1, 1, 2, 8])
    assert r.table() == [[1, 2], [1, 8], [-6], [8]]


def test_row_lengths_and_leading_zeros():
    for n in range(0, 8):
        c = [1] + list(range(1, n + 1))
        r = routh_array(c)
        assert len(r.rows) == n + 1
        assert [len(row) for row in r.rows] == [(n - i) // 2 + 1 for i in range(n + 1)]
    assert routh_array([0, 0, 1, 1, 2, 8]).first_column == [1, 1, -6, 8]


def test_zero_polynomial_raises():
    for c in ([0], [0, 0, 0], []):
        try:
            routh_array(c)
        except ValueError:
            pass
        else:
            raise AssertionError("no ValueError for %r" % (c,))


def test_constant_and_degree_one():
    assert routh_array([5]).sign_changes == 0 and is_hurwitz([5])
    assert is_hurwitz([2, 3]) and not is_hurwitz([2, -3]) and rhp_count([2, -3]) == 1


def test_scaling_does_not_change_the_count():
    rng = random.Random(7)
    for _ in range(200):
        c = random_poly(rng)
        k = rhp_count(c)
        assert rhp_count([-x for x in c]) == k
        assert rhp_count([Fraction(3, 2) * x for x in c]) == k


def test_float_and_fraction_input_are_exact():
    r = routh_array([1.0, 0.5, 0.75, 0.125])
    assert r.regular
    assert r.first_column == [1, Fraction(1, 2), Fraction(1, 2), Fraction(1, 8)]
    assert all(isinstance(x, Fraction) for x in r.first_column)
    r2 = routh_array([Fraction(1), Fraction(1, 2), Fraction(3, 4), Fraction(1, 8)])
    assert r.first_column == r2.first_column


def test_gain_range_third_order():
    # s^3 + 3 s^2 + 2 s + K is Hurwitz if and only if 0 < K < 6.
    for k2 in range(-4, 17):
        K = Fraction(k2, 2)
        assert is_hurwitz([1, 3, 2, K]) == (0 < K < 6)
    r = routh_array([1, 3, 2, 6])
    assert r.events == [("zero_row", 2, [3, 0, 6])]
    assert r.first_column == [1, 3, 6, 6]
    assert r.sign_changes == 0 and not is_hurwitz([1, 3, 2, 6])
    roots = cm.polyroots([1, 3, 2, 6])
    assert abs(roots[0] + 3) < 1e-9
    assert all(abs(z.real) < 1e-9 and abs(abs(z.imag) - 2 ** 0.5) < 1e-9 for z in roots[1:])


def test_epsilon_example():
    c = [1, 2, 2, 4, 11, 10]
    r = routh_array(c)
    assert r.events == [("epsilon", 2)]
    assert r.signs == [1, 1, 1, -1, 1, 1]
    assert r.sign_changes == 2 == rhp_true(c)
    # Row s^2 starts with (4 eps - 12) / eps.
    e = r.rows[3][0]
    assert isinstance(e, EpsFrac) and e.num == [-12, 4] and e.den == [0, 1]


def test_more_examples_from_the_page():
    r = routh_array([1, 10, 35, 50, 24])
    assert r.first_column == [1, 10, 30, 42, 24] and is_hurwitz([1, 10, 35, 50, 24])
    r = routh_array([1, 2, 3, 4, 5])
    assert r.first_column == [1, 2, 1, -6, 5] and r.sign_changes == 2 == rhp_true([1, 2, 3, 4, 5])


def test_hurwitz_determinants_are_products_of_the_first_column():
    assert hurwitz_determinants([1, 1, 2, 8]) == [1, -6, -48]
    assert hurwitz_determinants([1, 10, 35, 50, 24]) == [10, 300, 12600, 302400]
    rng = random.Random(11)
    checked = 0
    for _ in range(400):
        c = random_poly(rng, -5, 5)
        r = routh_array(c)
        if not r.regular:
            continue
        col = r.first_column[1:]
        prod, want = Fraction(1), []
        for x in col:
            prod *= x
            want.append(prod)
        assert hurwitz_determinants(c) == want
        checked += 1
    assert checked > 200


def test_random_polynomials_against_roots():
    # The verdict and the count agree with the roots when no root is near
    # the imaginary axis. Polynomials with a root within 1e-6 of the axis
    # are skipped, as the area rules ask.
    rng = random.Random(20261115)
    used = eps_used = 0
    for _ in range(1500):
        c = random_poly(rng)
        re = real_parts(c)
        if min(abs(x) for x in re) < 1e-6:
            continue
        r = routh_array(c)
        assert r.sign_changes == sum(1 for x in re if x > 0), c
        assert is_hurwitz(c) == all(x < 0 for x in re), c
        if is_hurwitz(c):
            assert all(x * c[0] > 0 for x in c), c
        used += 1
        eps_used += r.used_epsilon
    assert used > 1000 and eps_used > 50


def test_zero_rows_keep_the_count_and_find_the_axis_roots():
    # With zero rows and no epsilon, the count is exact even with roots on
    # the axis, and the axis roots of p are those of the first auxiliary
    # polynomial.
    rng = random.Random(5)
    seen = 0
    for _ in range(3000):
        c = random_poly(rng)
        r = routh_array(c)
        if r.regular or r.used_epsilon:
            continue
        re = real_parts(c)
        if any(AXIS <= abs(x) < 1e-2 for x in re):
            continue
        assert r.sign_changes == rhp_true(c), c
        aux = r.events[0][2]
        on_axis_p = sum(1 for x in re if abs(x) < AXIS)
        on_axis_aux = sum(1 for x in real_parts(aux) if abs(x) < AXIS)
        assert on_axis_p == on_axis_aux, c
        assert not is_hurwitz(c)
        seen += 1
    assert seen > 300


def test_built_zero_rows():
    # (s^2 + 1)(s + 1)(s - 2): one root in the right half plane and two on the axis.
    c = cm.polymul(cm.polymul([1, 0, 1], [1, 1]), [1, -2])
    r = routh_array(c)
    assert any(e[0] == "zero_row" for e in r.events)
    assert r.sign_changes == 1
    # (s^2 - 1)(s^2 + 4): roots symmetric about the origin, one in the right half plane.
    c = cm.polymul([1, 0, -1], [1, 0, 4])
    r = routh_array(c)
    assert r.events[0][0] == "zero_row" and r.sign_changes == 1


def test_epsilon_with_axis_roots_can_overcount():
    # The page warns that the epsilon method is proved only when p has no
    # root on the imaginary axis. Here p = (s^2 + 1)(s^3 + 2 s + 1) has two
    # roots in the right half plane, but the epsilon array shows 4 sign
    # changes. The Hurwitz verdict (False) is still right.
    c = [1, 0, 3, 1, 2, 1]
    assert cm.polymul([1, 0, 1], [1, 0, 2, 1]) == c
    r = routh_array(c)
    assert r.used_epsilon
    assert rhp_true(c) == 2 and r.sign_changes == 4
    assert not is_hurwitz(c)

History

The question of stability conditions for a polynomial was raised by J. C. Maxwell in his 1868 paper on governors. E. J. Routh answered it in his Adams Prize essay, A Treatise on the Stability of a Given State of Motion (1877), with the tabulation now named after him and the count of the roots with positive real part. A. Hurwitz, unaware of Routh's work, gave the conditions in determinant form in 1895, prompted by a question of A. Stodola on turbine regulators. Liénard and Chipart (1914) showed that about half of the determinant conditions suffice when the coefficients are positive. Gantmacher's book treats the singular cases in general, and short proofs of the counting rule appeared much later, among them Meinsma's in 1995.

References

  1. E. J. Routh, A Treatise on the Stability of a Given State of Motion, Particularly Steady Motion, Macmillan, London, 1877, the Adams Prize essay, with the tabulation of the coefficients and the count of the roots with positive real part
  2. A. Hurwitz, Ueber die Bedingungen, unter welchen eine Gleichung nur Wurzeln mit negativen reellen Theilen besitzt, Mathematische Annalen 46, 273-284, 1895, the determinant form of the conditions
  3. F. R. Gantmacher, The Theory of Matrices, Volume 2, AMS Chelsea Publishing, 2000 (reprint of the Chelsea edition of 1959), Chapter XV, The problem of Routh-Hurwitz and related questions (Routh's scheme, its singular cases, and the Hurwitz determinants)
  4. G. Meinsma, Elementary proof of the Routh-Hurwitz test, Systems and Control Letters 25(4), 237-242, 1995, the reduction of the degree by one and the continuity argument that the correctness proof follows
  5. Katsuhiko Ogata, Modern Control Engineering, fifth edition, Prentice Hall, 2010, Chapter 5 (Routh's stability criterion, with the special cases of a zero first entry and a row of zeros)

Where this leads

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