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 std::cosh;
28 using std::exp;
29 using std::sinh;
30 using std::sqrt;
31
32 using T = value_type_t<EigMat>;
33 T a = A(0, 0), b = A(0, 1), c = A(1, 0), d = A(1, 1), delta;
34 delta = sqrt(square(a - d) + 4 * b * c);
35
36 Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> B(2, 2);
37 T half_delta = 0.5 * delta;
38 T cosh_half_delta = cosh(half_delta);
39 T sinh_half_delta = sinh(half_delta);
40 T exp_half_a_plus_d = exp(0.5 * (a + d));
41 T Two_exp_sinh = 2 * exp_half_a_plus_d * sinh_half_delta;
42 T delta_cosh = delta * cosh_half_delta;
43 T ad_sinh_half_delta = (a - d) * sinh_half_delta;
44
45 B(0, 0) = exp_half_a_plus_d * (delta_cosh + ad_sinh_half_delta);
46 B(0, 1) = b * Two_exp_sinh;
47 B(1, 0) = c * Two_exp_sinh;
48 B(1, 1) = exp_half_a_plus_d * (delta_cosh - ad_sinh_half_delta);
49
50 // use pade approximation if cosh & sinh ops overflow to NaN
51 if (B.hasNaN()) {
52 return matrix_exp_pade(A);
53 } else {
54 return B / delta;
55 }
56}
57
58} // namespace math
59} // namespace stan
60
61#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:15
fvar< T > sinh(const fvar< T > &x)
Definition sinh.hpp:13
fvar< T > sqrt(const fvar< T > &x)
Definition sqrt.hpp:17
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:13
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...
Definition fvar.hpp:9