Skip to content

Commit 29f2933

Browse files
author
Yi Zhang
committed
use pade approx for matrix_exp_2x2 when cosh & sinh ops overflow
1 parent 20224ff commit 29f2933

2 files changed

Lines changed: 15 additions & 1 deletion

File tree

stan/math/prim/fun/matrix_exp_2x2.hpp

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,12 @@ matrix_exp_2x2(const EigMat& A) {
4747
B(1, 0) = c * Two_exp_sinh;
4848
B(1, 1) = exp_half_a_plus_d * (delta_cosh - ad_sinh_half_delta);
4949

50-
return B / delta;
50+
// use pade approximation if cosh & sinh ops overflow to NaN
51+
if ((B.array() != B.array()).any()) {
52+
return matrix_exp_pade(A);
53+
} else {
54+
return B / delta;
55+
}
5156
}
5257

5358
} // namespace math

test/unit/math/prim/fun/matrix_exp_2x2_test.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,12 @@ TEST(MathMatrixPrimMat, matrix_exp_2x2_2x2_2) {
2020

2121
EXPECT_MATRIX_FLOAT_EQ(m2, stan::math::matrix_exp_2x2(m1));
2222
}
23+
24+
TEST(MathMatrixPrimMat, matrix_exp_2x2_2x2_overflow) {
25+
// example from issue https://github.com/stan-dev/math/issues/2615
26+
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> m1(2, 2), m2(2, 2);
27+
m1 << -3.3228,0.533302,1.2242,-4.04844;
28+
double t = 800.0;
29+
m2 << 0.0, 0.0, 0.0, 0.0;
30+
EXPECT_MATRIX_FLOAT_EQ(m2, stan::math::matrix_exp_2x2(m1 * t));
31+
}

0 commit comments

Comments
 (0)