Skip to content

MatrixExpPade never scales the matrix, so Pade results are inaccurate for large ‖Qt‖ #137

Open

Description

@sdwfrost

Summary

MatrixExpPade in src/pijt.c computes the 1- and ∞-norms of At before At has been filled in. At that point At is still all zeros from R_Calloc. So l1 = linf = 0, K = -Inf, npower is set to NA_INTEGER and then reset to 0. Scaling and squaring is therefore never done. The order-8 Pade approximant is applied to the unscaled At, and its accuracy degrades as ‖At‖ grows.

This code is reached by MatrixExp(..., method = "pade"), and by msm(..., use.expm = FALSE) when Q has repeated or complex eigenvalues. The default use.expm = TRUE is not affected.

Reproducible example

library(msm)
Q <- rbind(c(0, .9, .01, .001), c(.05, 0, .01, 1.5), c(1.8, .01, 0, .02), c(.02, .05, 1.2, 0))
diag(Q) <- -rowSums(Q)                    # complex eigenvalues, so method = "pade" really uses Pade
ts <- c(0.5, 1, 3, 6, 17, 50)
err <- sapply(ts, function(t) max(abs(MatrixExp(Q, t, method = "pade") - expm::expm(Q * t))))
print(data.frame(t = ts, max_abs_error = signif(err, 3)))

Maximum absolute error in the transition probability matrix:

t msm 1.8.2 (CRAN, and master at c5c765c) with the fix below
0.5 2.22e-16 1.67e-15
1 1.76e-13 2.39e-15
3 2.25e-07 5.83e-15
6 1.25e-04 1.05e-14
17 3.33e-02 1.44e-15
50 3.04e-01 8.22e-15

Proposed fix

Since ‖At‖ = t‖A‖, take the norms of A and multiply by t:

--- a/src/pijt.c
+++ b/src/pijt.c
@@ -229,8 +229,8 @@ MatrixExpPade(double *ExpAt, double *A, int n, double t)
   double * At = workspace + N;
   double * Num = workspace + 2*N;
   double * Denom = workspace + 3*N;
-  double l1 = F77_CALL(dlange)("1", &n, &n, At, &n, 0 FCONE); /* L-1 norm */
-  double linf = F77_CALL(dlange)("i", &n, &n, At, &n, Temp FCONE); /* L-Infinity norm */
+  double l1 = t * F77_CALL(dlange)("1", &n, &n, A, &n, 0 FCONE); /* L-1 norm of At */
+  double linf = t * F77_CALL(dlange)("i", &n, &n, A, &n, Temp FCONE); /* L-Infinity norm of At */
   double K = (log(l1) + log(linf))/log(4);
   int npower = (R_FINITE(K) ? (int)(K)+4 : NA_INTEGER);
   double scale = 1;

With this change, tests/testthat passes (606 expectations, 0 failures, with the tests marked skip-on-CRAN skipped).

Activity

  1. chjackson commented on Oct 18, 2026

    @chjackson
    Owner

    Thanks - I've applied this fix, though I think it is only of academic interest, as msm defers to the expm package for matrix exponentiation in routine use. I'd happily remove the old alternative methods, but I'm curious if there is a case where the expm procedure doesn't work as well?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions