Skip to main content

lib_jsl_linalg/
equations.rs

1//! Linear and quadratic matrix equations: Sylvester, continuous and discrete Lyapunov, and the
2//! continuous and discrete algebraic Riccati equations, with SciPy's names and conventions.
3//!
4//! The linear equations are solved by the Bartels-Stewart method: reduce the coefficient matrices
5//! to complex Schur form, so that the transformed equation is triangular and can be solved column
6//! by column. The Riccati equations are solved by a structured iteration (the matrix sign function
7//! for the continuous equation, the doubling algorithm for the discrete one) followed by Newton
8//! refinement, each step of which is a Lyapunov equation.
9//!
10//! See the book entry [Matrix functions and matrix equations](https://jwkunz.github.io/lib_jsl/book/linear_algebra/matrix-equations.html).
11
12use crate::dense::{Mat, lincomb, matmul, norm1, require_square};
13use crate::eig::schur_unbalanced;
14use crate::error::{LinalgError, Result};
15use crate::lu::LuFactorization;
16use crate::scalar::Scalar;
17use crate::LeastSquaresSvd;
18use ndarray::{Array2, ArrayBase, Data, Ix2};
19use num_complex::Complex;
20
21type C = Complex<f64>;
22/// The four coefficient matrices of a Riccati equation, `(A, B, Q, R)`.
23type Coefficients = (Mat<C>, Mat<C>, Mat<C>, Mat<C>);
24
25fn complex<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>) -> Result<Mat<C>> {
26    let m = Mat::from_array(a)?;
27    Ok(Mat { rows: m.rows, cols: m.cols, data: m.data.iter().map(|v| v.to_complex()).collect() })
28}
29
30fn back<T: Scalar>(m: Mat<C>) -> Array2<T> {
31    Mat { rows: m.rows, cols: m.cols, data: m.data.into_iter().map(T::from_complex).collect() }.into_array()
32}
33
34fn shape(what: &str, got: (usize, usize), want: (usize, usize)) -> Result<()> {
35    if got == want { Ok(()) } else { Err(LinalgError::Shape(format!("{what} is {} × {}, expected {} × {}", got.0, got.1, want.0, want.1))) }
36}
37
38fn hermitian_part(x: &Mat<C>) -> Mat<C> {
39    lincomb(C::new(0.5, 0.0), x, C::new(0.5, 0.0), &x.adjoint())
40}
41
42fn max_abs(m: &Mat<C>) -> f64 {
43    m.data.iter().fold(0.0, |a, v| a.max(v.norm()))
44}
45
46/// Solves `(R + σ I) y = f` for upper triangular `R`, in place.
47fn shifted_back_substitution(r: &Mat<C>, sigma: C, y: &mut [C], tiny: f64) -> Result<()> {
48    let n = r.rows;
49    for i in (0..n).rev() {
50        let s = (i + 1..n).fold(C::new(0.0, 0.0), |acc, k| acc + r.at(i, k) * y[k]);
51        let d = r.at(i, i) + sigma;
52        if d.norm() <= tiny {
53            return Err(LinalgError::Singular(i));
54        }
55        y[i] = (y[i] - s) / d;
56    }
57    Ok(())
58}
59
60fn column(m: &Mat<C>, j: usize) -> Vec<C> {
61    (0..m.rows).map(|i| m.at(i, j)).collect()
62}
63
64fn set_column(m: &mut Mat<C>, j: usize, v: &[C]) {
65    for (i, &x) in v.iter().enumerate() {
66        *m.at_mut(i, j) = x;
67    }
68}
69
70// ANCHOR: sylvester
71/// Bartels-Stewart for `A X + X B = Q` on complex matrices.
72fn sylvester(a: &Mat<C>, b: &Mat<C>, q: &Mat<C>) -> Result<Mat<C>> {
73    let (r, u) = schur_unbalanced(a)?;
74    let (s, v) = schur_unbalanced(b)?;
75    // With A = U R Uᴴ and B = V S Vᴴ, Y = Uᴴ X V solves R Y + Y S = F = Uᴴ Q V.
76    let f = matmul(&matmul(&u.adjoint(), q), &v);
77    let (n, m) = (a.rows, b.rows);
78    let tiny = f64::EPSILON * (max_abs(&r) + max_abs(&s)).max(f64::MIN_POSITIVE);
79    let mut y = Mat::<C>::zeros(n, m);
80    // S is upper triangular, so column k of Y involves only columns j ≤ k:
81    // (R + s_kk I) y_k = f_k − Σ_{j<k} s_jk y_j.
82    for k in 0..m {
83        let mut rhs = column(&f, k);
84        for j in 0..k {
85            let sjk = s.at(j, k);
86            for i in 0..n {
87                rhs[i] -= sjk * y.at(i, j);
88            }
89        }
90        shifted_back_substitution(&r, s.at(k, k), &mut rhs, tiny)?;
91        set_column(&mut y, k, &rhs);
92    }
93    Ok(matmul(&matmul(&u, &y), &v.adjoint()))
94}
95// ANCHOR_END: sylvester
96
97// ANCHOR: stein
98/// The discrete Lyapunov (Stein) equation `A X Aᴴ − X + Q = 0` by the same Schur reduction.
99fn stein(a: &Mat<C>, q: &Mat<C>) -> Result<Mat<C>> {
100    let (r, u) = schur_unbalanced(a)?;
101    let f = matmul(&matmul(&u.adjoint(), q), &u);
102    let n = a.rows;
103    let tiny = f64::EPSILON * (1.0 + max_abs(&r) * max_abs(&r));
104    let mut y = Mat::<C>::zeros(n, n);
105    // Column j of R Y Rᴴ is R (conj(r_jj) y_j + w_j) with w_j = Σ_{l>j} conj(r_jl) y_l, so
106    // (conj(r_jj) R − I) y_j = −f_j − R w_j, solved from the last column to the first.
107    for j in (0..n).rev() {
108        let mut w = vec![C::new(0.0, 0.0); n];
109        for l in j + 1..n {
110            let c = r.at(j, l).conj();
111            for i in 0..n {
112                w[i] += c * y.at(i, l);
113            }
114        }
115        let mut rhs: Vec<C> = (0..n).map(|i| -f.at(i, j) - (i..n).fold(C::new(0.0, 0.0), |acc, k| acc + r.at(i, k) * w[k])).collect();
116        // (c R − I) y = rhs  ⇔  (R − I/c) y = rhs / c, for c = conj(r_jj) ≠ 0.
117        let c = r.at(j, j).conj();
118        if c.norm() <= tiny {
119            // c = 0: −y = rhs.
120            rhs.iter_mut().for_each(|v| *v = -*v);
121        } else {
122            rhs.iter_mut().for_each(|v| *v /= c);
123            shifted_back_substitution(&r, -c.inv(), &mut rhs, tiny / c.norm())?;
124        }
125        set_column(&mut y, j, &rhs);
126    }
127    Ok(matmul(&matmul(&u, &y), &u.adjoint()))
128}
129// ANCHOR_END: stein
130
131/// Solves the Sylvester equation `A X + X B = Q` for `X` (SciPy's `linalg.solve_sylvester`), with
132/// `A` `n × n`, `B` `m × m` and `Q` `n × m`. The solution is unique when no eigenvalue of `A` is
133/// the negative of an eigenvalue of `B`; otherwise [`LinalgError::Singular`] is returned.
134pub fn solve_sylvester<T: Scalar, S1: Data<Elem = T>, S2: Data<Elem = T>, S3: Data<Elem = T>>(
135    a: &ArrayBase<S1, Ix2>,
136    b: &ArrayBase<S2, Ix2>,
137    q: &ArrayBase<S3, Ix2>,
138) -> Result<Array2<T>> {
139    let (a, b, q) = (complex(a)?, complex(b)?, complex(q)?);
140    require_square(a.rows, a.cols)?;
141    require_square(b.rows, b.cols)?;
142    shape("Q", (q.rows, q.cols), (a.rows, b.rows))?;
143    Ok(back(sylvester(&a, &b, &q)?))
144}
145
146/// Solves the continuous Lyapunov equation `A X + X Aᴴ = Q` (SciPy's
147/// `linalg.solve_continuous_lyapunov`). For a stable `A` and `Q = −C Cᴴ`, `X` is the
148/// controllability Gramian.
149pub fn solve_continuous_lyapunov<T: Scalar, S1: Data<Elem = T>, S2: Data<Elem = T>>(a: &ArrayBase<S1, Ix2>, q: &ArrayBase<S2, Ix2>) -> Result<Array2<T>> {
150    let (a, q) = (complex(a)?, complex(q)?);
151    require_square(a.rows, a.cols)?;
152    shape("Q", (q.rows, q.cols), (a.rows, a.rows))?;
153    Ok(back(sylvester(&a, &a.adjoint(), &q)?))
154}
155
156/// Solves the discrete Lyapunov equation `A X Aᴴ − X + Q = 0` (SciPy's
157/// `linalg.solve_discrete_lyapunov`). The solution is unique when no product of two eigenvalues
158/// of `A` (one conjugated) equals 1; for `A` with spectral radius below 1 and `Q = B Bᴴ`, `X` is the
159/// controllability Gramian `Σ Aᵏ B Bᴴ (Aᴴ)ᵏ`.
160pub fn solve_discrete_lyapunov<T: Scalar, S1: Data<Elem = T>, S2: Data<Elem = T>>(a: &ArrayBase<S1, Ix2>, q: &ArrayBase<S2, Ix2>) -> Result<Array2<T>> {
161    let (a, q) = (complex(a)?, complex(q)?);
162    require_square(a.rows, a.cols)?;
163    shape("Q", (q.rows, q.cols), (a.rows, a.rows))?;
164    Ok(back(stein(&a, &q)?))
165}
166
167fn riccati_inputs<T: Scalar, S1: Data<Elem = T>, S2: Data<Elem = T>, S3: Data<Elem = T>, S4: Data<Elem = T>>(
168    a: &ArrayBase<S1, Ix2>,
169    b: &ArrayBase<S2, Ix2>,
170    q: &ArrayBase<S3, Ix2>,
171    r: &ArrayBase<S4, Ix2>,
172) -> Result<Coefficients> {
173    let (a, b, q, r) = (complex(a)?, complex(b)?, complex(q)?, complex(r)?);
174    require_square(a.rows, a.cols)?;
175    let (n, m) = (a.rows, b.cols);
176    shape("B", (b.rows, b.cols), (n, m))?;
177    shape("Q", (q.rows, q.cols), (n, n))?;
178    shape("R", (r.rows, r.cols), (m, m))?;
179    Ok((a, b, q, r))
180}
181
182/// `R⁻¹ M` by an LU factorisation of `R`.
183fn solve_left(r: &Mat<C>, m: &Mat<C>) -> Result<Mat<C>> {
184    let lu = LuFactorization::new(r.clone())?;
185    let mut out = Mat::zeros(m.rows, m.cols);
186    for j in 0..m.cols {
187        set_column(&mut out, j, &lu.solve_vec(&column(m, j)));
188    }
189    Ok(out)
190}
191
192fn sub(a: &Mat<C>, b: &Mat<C>) -> Mat<C> {
193    lincomb(C::new(1.0, 0.0), a, C::new(-1.0, 0.0), b)
194}
195
196fn add(a: &Mat<C>, b: &Mat<C>) -> Mat<C> {
197    lincomb(C::new(1.0, 0.0), a, C::new(1.0, 0.0), b)
198}
199
200/// Newton steps on a Riccati residual until it stops decreasing (at most `steps`).
201fn refine(mut x: Mat<C>, steps: usize, residual: impl Fn(&Mat<C>) -> Mat<C>, correction: impl Fn(&Mat<C>, &Mat<C>) -> Result<Mat<C>>) -> Mat<C> {
202    let mut res = residual(&x);
203    let mut size = norm1(&res);
204    for _ in 0..steps {
205        let Ok(delta) = correction(&x, &res) else { break };
206        let candidate = hermitian_part(&add(&x, &delta));
207        let res_c = residual(&candidate);
208        let size_c = norm1(&res_c);
209        // Stop unless the residual decreased (a NaN residual also stops).
210        if size_c.partial_cmp(&size) != Some(std::cmp::Ordering::Less) {
211            break;
212        }
213        (x, res, size) = (candidate, res_c, size_c);
214    }
215    x
216}
217
218// ANCHOR: care
219/// Solves the continuous algebraic Riccati equation `Aᴴ X + X A − X B R⁻¹ Bᴴ X + Q = 0` for the
220/// stabilising solution `X` (SciPy's `linalg.solve_continuous_are`, without its `e` and `s`
221/// options), for which `A − B R⁻¹ Bᴴ X` has all its eigenvalues in the left half-plane.
222///
223/// The Hamiltonian `H = [[A, −G], [−Q, −Aᴴ]]` with `G = B R⁻¹ Bᴴ` satisfies
224/// `H [I; X] = [I; X] (A − G X)`, so `[I; X]` spans its stable invariant subspace, the null space
225/// of `sign(H) + I`. The sign function is computed by Newton's iteration
226/// `Z ← (Z / c + c Z⁻¹) / 2` with determinant scaling `c = |det Z|^{1/2n}`; `X` follows by least
227/// squares and is polished by Newton (Kleinman) steps, each a continuous Lyapunov equation.
228/// Requires `(A, B)` stabilisable and no eigenvalues of `H` on the imaginary axis.
229pub fn solve_continuous_are<T: Scalar, S1: Data<Elem = T>, S2: Data<Elem = T>, S3: Data<Elem = T>, S4: Data<Elem = T>>(
230    a: &ArrayBase<S1, Ix2>,
231    b: &ArrayBase<S2, Ix2>,
232    q: &ArrayBase<S3, Ix2>,
233    r: &ArrayBase<S4, Ix2>,
234) -> Result<Array2<T>> {
235    let (a, b, q, r) = riccati_inputs(a, b, q, r)?;
236    let n = a.rows;
237    let g = matmul(&b, &solve_left(&r, &b.adjoint())?);
238    let ah = a.adjoint();
239    // The Hamiltonian.
240    let mut z = Mat::<C>::zeros(2 * n, 2 * n);
241    for i in 0..n {
242        for j in 0..n {
243            *z.at_mut(i, j) = a.at(i, j);
244            *z.at_mut(i, j + n) = -g.at(i, j);
245            *z.at_mut(i + n, j) = -q.at(i, j);
246            *z.at_mut(i + n, j + n) = -ah.at(i, j);
247        }
248    }
249    let mut converged = false;
250    for _ in 0..100 {
251        let lu = LuFactorization::new(z.clone()).map_err(|_| LinalgError::NoConvergence("the Hamiltonian has eigenvalues on the imaginary axis; sign iteration"))?;
252        let log_det = (0..2 * n).map(|i| lu.lu.at(i, i).norm().ln()).sum::<f64>();
253        let c = (log_det / (2 * n) as f64).exp();
254        let next = lincomb(C::new(0.5 / c, 0.0), &z, C::new(0.5 * c, 0.0), &lu.inverse());
255        let change = norm1(&sub(&next, &z));
256        z = next;
257        if change <= 1e-13 * norm1(&z) {
258            converged = true;
259            break;
260        }
261    }
262    if !converged {
263        return Err(LinalgError::NoConvergence("the matrix sign iteration"));
264    }
265    // [W12; W22 + I] X = −[W11 + I; W21], solved column by column in the least-squares sense.
266    let mut lhs = Array2::<C>::zeros((2 * n, n));
267    let mut rhs = Array2::<C>::zeros((2 * n, n));
268    let one = |yes: bool| C::new(if yes { 1.0 } else { 0.0 }, 0.0);
269    for i in 0..2 * n {
270        for j in 0..n {
271            lhs[(i, j)] = z.at(i, j + n) + one(i == j + n);
272            rhs[(i, j)] = -(z.at(i, j) + one(i == j));
273        }
274    }
275    let mut x = Mat::<C>::zeros(n, n);
276    for j in 0..n {
277        let sol = lhs.least_squares(&rhs.column(j))?.solution;
278        set_column(&mut x, j, sol.as_slice().expect("contiguous"));
279    }
280    let residual = |x: &Mat<C>| {
281        let xa = matmul(x, &a);
282        hermitian_part(&add(&sub(&add(&xa.adjoint(), &xa), &matmul(&matmul(x, &g), x)), &q))
283    };
284    let correction = |x: &Mat<C>, res: &Mat<C>| {
285        // (A − G X)ᴴ Δ + Δ (A − G X) = −Res.
286        let ac = sub(&a, &matmul(&g, x));
287        sylvester(&ac.adjoint(), &ac, &lincomb(C::new(-1.0, 0.0), res, C::new(0.0, 0.0), &Mat::zeros(n, n)))
288    };
289    Ok(back(refine(hermitian_part(&x), 10, residual, correction)))
290}
291// ANCHOR_END: care
292
293// ANCHOR: dare
294/// Solves the discrete algebraic Riccati equation
295/// `Aᴴ X A − X − Aᴴ X B (R + Bᴴ X B)⁻¹ Bᴴ X A + Q = 0` for the stabilising solution (SciPy's
296/// `linalg.solve_discrete_are`, without its `e` and `s` options), for which `A − B K` with
297/// `K = (R + Bᴴ X B)⁻¹ Bᴴ X A` has all its eigenvalues inside the unit circle.
298///
299/// The structure-preserving doubling algorithm (Chu, Fan, Lin and Wang 2004) starts from
300/// `A₀ = A`, `G₀ = B R⁻¹ Bᴴ`, `H₀ = Q` and iterates
301/// `A ← A (I + G H)⁻¹ A`, `G ← G + A (I + G H)⁻¹ G Aᴴ`, `H ← H + Aᴴ H (I + G H)⁻¹ A`;
302/// `H` converges quadratically to `X`, which is then polished by Newton (Hewer) steps, each a
303/// discrete Lyapunov equation. Requires `(A, B)` stabilisable and no eigenvalues of the
304/// symplectic pencil on the unit circle; `A` need not be invertible.
305pub fn solve_discrete_are<T: Scalar, S1: Data<Elem = T>, S2: Data<Elem = T>, S3: Data<Elem = T>, S4: Data<Elem = T>>(
306    a: &ArrayBase<S1, Ix2>,
307    b: &ArrayBase<S2, Ix2>,
308    q: &ArrayBase<S3, Ix2>,
309    r: &ArrayBase<S4, Ix2>,
310) -> Result<Array2<T>> {
311    let (a, b, q, r) = riccati_inputs(a, b, q, r)?;
312    let n = a.rows;
313    let eye = Mat::<C>::identity(n);
314    let (mut ak, mut gk, mut hk) = (a.clone(), matmul(&b, &solve_left(&r, &b.adjoint())?), q.clone());
315    let mut converged = false;
316    for _ in 0..100 {
317        let w = add(&eye, &matmul(&gk, &hk));
318        let t1 = solve_left(&w, &ak).map_err(|_| LinalgError::NoConvergence("the doubling algorithm (I + G H singular)"))?;
319        let t2 = solve_left(&w, &gk)?;
320        let h_next = add(&hk, &matmul(&matmul(&ak.adjoint(), &hk), &t1));
321        let g_next = add(&gk, &matmul(&matmul(&ak, &t2), &ak.adjoint()));
322        ak = matmul(&ak, &t1);
323        let change = norm1(&sub(&h_next, &hk));
324        (gk, hk) = (g_next, h_next);
325        if change <= 1e-14 * norm1(&hk) {
326            converged = true;
327            break;
328        }
329    }
330    if !converged {
331        return Err(LinalgError::NoConvergence("the doubling algorithm"));
332    }
333    let bh = b.adjoint();
334    let gain = |x: &Mat<C>| -> Result<Mat<C>> {
335        let bhx = matmul(&bh, x);
336        solve_left(&add(&r, &matmul(&bhx, &b)), &matmul(&bhx, &a))
337    };
338    let residual = |x: &Mat<C>| {
339        let ah_x = matmul(&a.adjoint(), x);
340        let k = gain(x).unwrap_or_else(|_| Mat::zeros(b.cols, n));
341        hermitian_part(&add(&sub(&sub(&matmul(&ah_x, &a), x), &matmul(&matmul(&ah_x, &b), &k)), &q))
342    };
343    let correction = |x: &Mat<C>, res: &Mat<C>| {
344        // (A − B K)ᴴ Δ (A − B K) − Δ + Res = 0.
345        let ac = sub(&a, &matmul(&b, &gain(x)?));
346        stein(&ac.adjoint(), res)
347    };
348    Ok(back(refine(hermitian_part(&hk), 10, residual, correction)))
349}
350// ANCHOR_END: dare
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355    use crate::{expm, schur_complex};
356    use ndarray::array;
357
358    fn max_diff(a: &Array2<f64>, b: &Array2<f64>) -> f64 {
359        (a - b).iter().fold(0.0, |m, v| m.max(v.abs()))
360    }
361
362    fn sample() -> (Array2<f64>, Array2<f64>, Array2<f64>, Array2<f64>) {
363        let a = array![[0.9, 0.2, 0.0, -0.3], [-0.1, 0.8, 0.3, 0.1], [0.0, -0.2, 0.7, 0.4], [0.5, 0.0, -0.6, 1.1]];
364        let b = array![[1.0, 0.0], [0.5, 0.2], [0.0, 1.0], [0.3, -0.4]];
365        let q = array![[2.0, 0.1, 0.0, 0.0], [0.1, 1.0, 0.0, 0.2], [0.0, 0.0, 1.5, 0.0], [0.0, 0.2, 0.0, 0.5]];
366        let r = array![[1.0, 0.2], [0.2, 0.5]];
367        (a, b, q, r)
368    }
369
370    #[test]
371    fn schur_reconstructs_the_matrix() {
372        let (a, ..) = sample();
373        let (t, z) = schur_complex(&a).unwrap();
374        let back = z.dot(&t).dot(&z.t().mapv(|v| v.conj()));
375        assert!(back.iter().zip(a.iter()).all(|(x, y)| (x - C::new(*y, 0.0)).norm() < 1e-13));
376        for i in 0..4 {
377            for j in 0..i {
378                assert!(t[(i, j)].norm() < 1e-14);
379            }
380        }
381    }
382
383    #[test]
384    fn sylvester_and_lyapunov_residuals() {
385        let (a, _, q, _) = sample();
386        let bm = array![[-0.5, 1.0], [0.0, 2.0]];
387        let qs = array![[1.0, 2.0], [0.0, -1.0], [3.0, 1.0], [0.5, 0.5]];
388        let x = solve_sylvester(&a, &bm, &qs).unwrap();
389        assert!(max_diff(&(a.dot(&x) + x.dot(&bm)), &qs) < 1e-12);
390        let x = solve_continuous_lyapunov(&a, &q).unwrap();
391        assert!(max_diff(&(a.dot(&x) + x.dot(&a.t())), &q) < 1e-12);
392        let x = solve_discrete_lyapunov(&a, &q).unwrap();
393        assert!(max_diff(&(a.dot(&x).dot(&a.t()) - &x + &q), &Array2::zeros((4, 4))) < 1e-11);
394    }
395
396    #[test]
397    fn riccati_solutions_are_stabilising() {
398        let (a, b, q, r) = sample();
399        let rinv = array![[0.5 / 0.46, -0.2 / 0.46], [-0.2 / 0.46, 1.0 / 0.46]];
400        let x = solve_continuous_are(&a, &b, &q, &r).unwrap();
401        let res = a.t().dot(&x) + x.dot(&a) - x.dot(&b).dot(&rinv).dot(&b.t()).dot(&x) + &q;
402        assert!(res.iter().all(|v| v.abs() < 1e-11), "{res}");
403        let closed = &a - &b.dot(&rinv).dot(&b.t()).dot(&x);
404        assert!(crate::EigVals::eigvals(&closed).unwrap().iter().all(|l| l.re < 0.0));
405
406        let x = solve_discrete_are(&a, &b, &q, &r).unwrap();
407        let s = &r + &b.t().dot(&x).dot(&b);
408        let sinv = crate::Inverse::inv(&s).unwrap();
409        let k = sinv.dot(&b.t()).dot(&x).dot(&a);
410        let res = a.t().dot(&x).dot(&a) - &x - a.t().dot(&x).dot(&b).dot(&k) + &q;
411        assert!(res.iter().all(|v| v.abs() < 1e-11), "{res}");
412        let closed = &a - &b.dot(&k);
413        assert!(crate::EigVals::eigvals(&closed).unwrap().iter().all(|l| l.norm() < 1.0));
414    }
415
416    #[test]
417    fn expm_of_a_rotation_generator() {
418        for theta in [0.001, 0.3, 2.0, 40.0] {
419            let a = array![[0.0, -theta], [theta, 0.0]];
420            let e = expm(&a).unwrap();
421            let want = array![[theta.cos(), -theta.sin()], [theta.sin(), theta.cos()]];
422            assert!(max_diff(&e, &want) < 1e-12 * theta.max(1.0), "θ = {theta}: {e}");
423        }
424        // A nilpotent matrix: e^N = I + N + N²/2.
425        let nmat = array![[0.0, 1.0, 2.0], [0.0, 0.0, 3.0], [0.0, 0.0, 0.0]];
426        let want = array![[1.0, 1.0, 3.5], [0.0, 1.0, 3.0], [0.0, 0.0, 1.0]];
427        assert!(max_diff(&expm(&nmat).unwrap(), &want) < 1e-14);
428    }
429}