Automatic Differentiation
 
Loading...
Searching...
No Matches
matrix_exp_2x2.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_FUN_MATRIX_EXP_2X2_HPP
2#define STAN_MATH_PRIM_FUN_MATRIX_EXP_2X2_HPP
3
10#include <cmath>
11
12namespace stan {
13namespace math {
14
24template <typename EigMat, require_eigen_t<EigMat>* = nullptr>
25Eigen::Matrix<value_type_t<EigMat>, Eigen::Dynamic, Eigen::Dynamic>
26matrix_exp_2x2(const EigMat& A) {
27 using T = value_type_t<EigMat>;
28 T a = A(0, 0), b = A(0, 1), c = A(1, 0), d = A(1, 1), delta;
29 delta = sqrt(square(a - d) + 4 * b * c);
30
31 Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> B(2, 2);
32 T half_delta = 0.5 * delta;
33 T cosh_half_delta = cosh(half_delta);
34 T sinh_half_delta = sinh(half_delta);
35 T exp_half_a_plus_d = exp(0.5 * (a + d));
36 T Two_exp_sinh = 2 * exp_half_a_plus_d * sinh_half_delta;
37 T delta_cosh = delta * cosh_half_delta;
38 T ad_sinh_half_delta = (a - d) * sinh_half_delta;
39
40 B(0, 0) = exp_half_a_plus_d * (delta_cosh + ad_sinh_half_delta);
41 B(0, 1) = b * Two_exp_sinh;
42 B(1, 0) = c * Two_exp_sinh;
43 B(1, 1) = exp_half_a_plus_d * (delta_cosh - ad_sinh_half_delta);
44
45 // use pade approximation if cosh & sinh ops overflow to NaN
46 if (B.hasNaN()) {
47 return matrix_exp_pade(A);
48 } else {
49 return B / delta;
50 }
51}
52
53} // namespace math
54} // namespace stan
55
56#endif
typename value_type< T >::type value_type_t
Helper function for accessing underlying type.
fvar< T > cosh(const fvar< T > &x)
Definition cosh.hpp:16
fvar< T > sinh(const fvar< T > &x)
Definition sinh.hpp:15
fvar< T > sqrt(const fvar< T > &x)
Definition sqrt.hpp:18
Eigen::Matrix< value_type_t< EigMat >, Eigen::Dynamic, Eigen::Dynamic > matrix_exp_2x2(const EigMat &A)
Return the matrix exponential of a 2x2 matrix.
Eigen::Matrix< value_type_t< EigMat >, EigMat::RowsAtCompileTime, EigMat::ColsAtCompileTime > matrix_exp_pade(const EigMat &arg)
Computes the matrix exponential, using a Pade approximation, coupled with scaling and squaring.
fvar< T > square(const fvar< T > &x)
Definition square.hpp:12
fvar< T > exp(const fvar< T > &x)
Definition exp.hpp:15
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...