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
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Edward John Routh, 1877
The Routh array is a table of numbers built from the coefficients of a real polynomial . 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 cross products. The number of sign changes in the first column of the table equals the number of roots of 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 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 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 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 with , written with the highest power first, count its roots in the open right half plane , counted with multiplicity, and decide whether all roots lie in the open left half plane. The usual source of is the characteristic polynomial of a linear system, or the denominator of a closed-loop transfer function.
Notation. Row belongs to the power , for , and has entries . The first column is . An entry outside a row counts as . is the number of sign changes in , and and are the numbers of roots of in the open right half plane and on the imaginary axis.
The algorithm
ROUTH-ARRAY(a_0, ..., a_n)- 1
remove zero leading coefficients; if no coefficient is left then error - 2
row_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 - 3
for i ← 1 to n do - 4
if i ≥ 2 then - 5
c ← row_{i-1}[0] - 6
for 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 - 7
if every entry of row_i is 0 then ▷ zero row - 8
d ← n - i + 1; A(s) ← Σ_j row_{i-1}[j] · s^(d-2j) ▷ auxiliary polynomial - 9
row_i[j] ← (d - 2j) · row_{i-1}[j] for every j ▷ the coefficients of A'(s) - 10
else if row_i[0] = 0 then ▷ zero first entry - 11
row_i[0] ← ε ▷ ε is a positive infinitesimal - 12
V ← number of sign changes in row_0[0], ..., row_n[0], each sign taken as ε → 0+ - 13
return 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 and the next row is . Lines L7 to L9 handle a row of zeros: the row above defines an even or odd auxiliary polynomial of degree , 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 , the later entries become rational functions of , and line L12 uses their signs for small . A row may be multiplied by a positive number at any point without changing , 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 as a quotient of two polynomials in ; the sign as 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 .
Example
The regular case. For :
| row | power | entries |
|---|---|---|
| 0 | , | |
| 1 | , | |
| 2 | ||
| 3 |
The first column has two sign changes, so has two roots in the right half plane. Indeed , with the roots and . All coefficients of are positive, so the coefficient signs alone would not show this.
A gain range. For the rows are , , and . The first column is positive exactly when , so the companion matrix of is Hurwitz for exactly these gains. For it is , with two sign changes.
A zero row. At , row 2 is . The row above gives , and row 2 becomes the coefficient of . Then row 3 is . The first column has no sign change, so no root lies in the right half plane. The roots of are , and they are roots of : . So has one root in the left half plane and two on the axis, and it is not Hurwitz, although .
A zero first entry. For :
| row | power | entries |
|---|---|---|
| 0 | , , | |
| 1 | , , | |
| 2 | , | |
| 3 | , | |
| 4 | ||
| 5 |
For small the signs are , so . The roots are , and : 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, has no root on the imaginary axis and .
- Zero rows only (proved). If zero rows occur and no zero first entry does, then . The roots of on the imaginary axis are exactly those of the first auxiliary polynomial , with multiplicity, and has roots in the open left half plane.
- One zero first entry (proved). If exactly one substitution and no zero row occur, and has no root on the imaginary axis, then . With several substitutions the implementation reuses the same ; the count was correct on all the random tests, but this case is not proved.
- Roots on the axis with (counterexample). If has roots on the imaginary axis and an substitution occurs, can be larger than . See Pitfalls.
- The Hurwitz decision (proved).
is_hurwitz(p)is true if and only if all roots of 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 are .
- Termination (proved). The loop runs 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 to and no root within of the axis, more than 50 of which need the 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 be real with and . For a real polynomial , is the number of its roots in the open right half plane and the number on the imaginary axis, both counted with multiplicity. is if the condition holds and 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 with a parity, , 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 of the array, with entries , stands for the polynomial
which has the parity of . So and are the parts of with the parity of and of , and . Write and, when , , a polynomial of degree whose two parts are and ().
Lemma 0 (the cross product rule). If and , line L6 computes
Proof. With $u = $ row and $c = $ row , the coefficient of in is , and in it is . The coefficient of is . So , and is line L6.
Two facts about roots
Fact 1 (continuity of roots). Let be real polynomials whose coefficients depend continuously on in an interval , with constant degree . If no , , has a root on the imaginary axis, then is constant on . Reason. By Rouché's theorem, for near the roots of lie in small discs around the roots of , 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 is locally constant, and is connected.
Fact 2 (a root to infinity). If moreover , coefficientwise, the leading coefficient of tends to , and has degree , then for close to , roots of lie in small discs around the roots of and the last root leaves every bounded set. Reason. Rouché's theorem on the discs around the roots of gives roots in the discs; on a bounded set outside the discs is bounded away from for near , because uniformly there.
Lemma 1: the imaginary axis
Let and be real polynomials of opposite parity. Then for real , if and only if and .
Proof. An even real polynomial takes real values at , and an odd one takes purely imaginary values. So one of , is the real part of the sum and the other is times its imaginary part.
Now let and have opposite parity, and let . Since and , is also a common divisor of the same degree, so , and has a parity. Then and have parities, opposite to each other, and they are coprime. By Lemma 1, has no root on the axis. Hence:
Corollary 1. If with , of opposite parity and , then the roots of on the imaginary axis are exactly the roots of on the axis, with the same multiplicities. In particular .
Lemma 2: one step lowers the degree
Let have degree , where has the parity of and the leading coefficient , and has the other parity and the coefficient at . Let , and . Then:
(a) has degree , its parts are (leading coefficient ) and , and ;
(b) , with the same roots on the axis;
(c) .
Proof. (a) has the parity of and the leading term , so has the parity of and degree at most . A common divisor of and divides , and a common divisor of and divides .
(b) Corollary 1 for and for , with the same .
(c) Let , , , and for
Then and . The polynomial has the parity of , and . By Lemma 1, no has a root on the axis. The coefficient of in is , which is nonzero for ; the coefficient of is for every , because and contribute nothing to that power. So has constant degree on , and has degree .
By Fact 1, for . By Fact 2, for near , roots of lie near the roots of , which are off the axis, so they contribute ; the last root leaves every bounded set. The sum of all roots of is . The roots of do not move and the other roots of stay bounded, so , whose real part tends to if and to if . So , and adding on both sides gives (c).
By Lemma 0, when and , Lemma 2 applied to (with , ) gives . So the array is the sequence of Lemma 2.
Theorem 1: the regular case
If no special case occurs, then and , the number of sign changes in .
Proof. All are nonzero. For , Lemma 2 gives and . is a nonzero constant, with . Adding up, and .
Lemma 3: the derivative of an even or odd polynomial
Let be even or odd, of degree . Then has degree , its parts are and , , and the roots of on the axis are the multiple roots of on the axis, each with its multiplicity lowered by one.
Proof. has the other parity and degree . Let for ; its degree is for every . For , Lemma 1 says if and only if . Let be a root of of multiplicity and write with . Then
and the bracket equals at , so for the multiplicity of in is exactly . Let be the product of over the distinct roots of on the axis. Conjugate roots have equal multiplicities, so is real. divides every , and has no root on the axis for , so by Fact 1 is constant on .
As , , which has the same degree, a simple root at each axis root of , and the roots of off the axis. Near a simple root of , the implicit function theorem gives a root of with at . With , , one finds and . So , and lies in the open left half plane for small . The roots of off the axis keep their side for small . Hence for small , and so for : .
Since the roots of are symmetric about the origin, has as many roots in the left as in the right half plane, so .
Theorem 2: zero rows
Suppose zero rows occur and no zero first entry does. Let be the auxiliary polynomial of the first zero row. Then , the roots of on the imaginary axis are those of with multiplicity, and has 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 times the nonzero first entry of the row above. So in line L5 throughout.
Induction on the number of zero rows; is Theorem 1. Let and let row be the first zero row, so before the replacement and , of degree . Lemma 2 for gives
and the same roots on the axis for and . (For , .) After the replacement, row holds the coefficients of and row those of , and every later row depends only on these two rows. So rows are the array of , whose parts are and ; it has zero rows and no zero first entry. By induction and Lemma 3, . Adding the two counts, . The left half plane count is .
Theorem 3: one zero first entry
Suppose exactly one substitution occurs, in row , no zero row occurs, and has no root on the imaginary axis. Then , with the signs taken as .
Proof. Rows have nonzero first entries, so Lemma 2 for gives and . Here , where has a zero coefficient at . For real let
whose parts are and . The rows that the algorithm computes, with as a symbol, are rational functions of , and every first entry , , is a nonzero rational function, since no further special case occurs. Only finitely many make a numerator or a denominator of some entry vanish. For every other real , evaluating the entries at gives the numerical array of , with the same operations and nonzero divisors, and that array is regular. A nonzero rational function has a constant sign on some interval , namely its sign as . So for small , Theorem 1 gives , which is the count of line L12 on rows .
As , with the constant degree and leading coefficient , and has no root on the axis. By Fact 1 (on a small interval around , where no has a root on the axis, by continuity), for small . Adding, .
What is not proved. If a second substitution occurs, the implementation uses the same , so the polynomial and the perturbation both depend on , 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 and zero rows are also not covered here.
The hypothesis on the axis is needed. has , so the substitution happens in row 1. The signs as are , so , but : the roots are , and . In the proof, 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 , is true if and only if every root of has a negative real part.
Proof. If no special case occurs and , Theorem 1 gives . Conversely, let be Hurwitz. Then is a product of factors with and with , so all coefficients of are nonzero and have the sign of ; in particular . Lemma 2 applies to and gives and ; has degree , so it is Hurwitz. By induction every is Hurwitz of degree , so its first two coefficients and are nonzero and of the same sign. Hence no row is zero, no first entry is zero, and .
Theorem 5: the Hurwitz determinants
Let be the Hurwitz matrix of , (with for or ), and its leading principal minor of order . In the regular case, for .
Proof. Induction on . Row of is and row is , both starting in column . Subtract times row from row , for each . This adds multiples of earlier rows to later rows, so it does not change any leading principal minor. Row becomes , which is the row of starting in column . Now column 1 is , and the matrix left after deleting row 1 and column 1 is the Hurwitz matrix of , of degree , whose coefficients are . So , with . The array of is rows of the array of , so by induction , and .
With , a positive first column is thus the same as , which is Hurwitz's form of the criterion.
Termination and cost
The loop in line L3 runs times. Row has entries, each computed once by line L6 with two multiplications, a subtraction and a division, and lines L7 to L11 cost per row. So the algorithm stops after arithmetic operations on the entries, which are numbers in the regular case and with zero rows, and rational functions of after a substitution.
Complexity
- Time. Row has entries, each made by two multiplications, one subtraction and one division. In all that is about cross products, arithmetic operations. A zero row costs more.
- Space. numbers for the whole table, or 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 . With symbolic coefficients, such as a gain , the entries are rational functions of , and the conditions become polynomial inequalities in .
- The case. The entries become rational functions of whose degree can grow with each row, so the cost of that case is higher than 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 .
- Symbolic. The table can be built with unknown parameters, which gives the parameter region in which is Hurwitz.
- Scaling. Multiplying a row by a positive number, or by a nonzero number, does not change .
- Same as Gaussian elimination. The table is the elimination of the Hurwitz matrix of without pivoting, which is why (see Gaussian elimination). It is also a form of the Euclidean algorithm on the even and odd parts of , and the rows with polynomial meaning form a sequence of the Sturm kind.
Variants and improvements
- Hurwitz determinants. The conditions (for ) 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 , build the table for .
- 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 , one can apply the table to or to the reversed polynomial , 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 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. means no root in the right half plane; it does not exclude roots on the axis. The example at has and roots . The polynomial is Hurwitz only if no special case occurs and .
- The method with roots on the axis. For , row 1 starts with , the method gives the signs and , but has only two roots in the right half plane, . The roots on the axis are counted as if they were in the right half plane. When 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 is not Hurwitz (for ). 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.
# 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
- 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
- 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
- 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)
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 43YJD3 Edit this page History Report an error Markdown