1 #ifndef STAN__AGRAD__REV__MATRIX__LOG_SUM_EXP_HPP
2 #define STAN__AGRAD__REV__MATRIX__LOG_SUM_EXP_HPP
23 template <
int R,
int C>
24 double log_sum_exp_as_double(
const Eigen::Matrix<var,R,C>& x) {
25 using std::numeric_limits;
28 double max = -numeric_limits<double>::infinity();
29 for (
int i = 0; i < x.size(); ++i)
33 for (
int i = 0; i < x.size(); ++i)
34 if (x(i) != -numeric_limits<double>::infinity())
35 sum +=
exp(x(i).val() -
max);
36 return max +
log(sum);
39 class log_sum_exp_matrix_vari :
public op_matrix_vari {
41 template <
int R,
int C>
42 log_sum_exp_matrix_vari(
const Eigen::Matrix<var,R,C>& x) :
43 op_matrix_vari(log_sum_exp_as_double(x), x) {
46 for (
size_t i = 0; i <
size_; ++i) {
58 template <
int R,
int C>
60 return var(
new log_sum_exp_matrix_vari(x));
fvar< T > log_sum_exp(const fvar< T > &x1, const fvar< T > &x2)
double max(const double a, const double b)
fvar< T > sum(const Eigen::Matrix< fvar< T >, R, C > &m)
double calculate_chain(const double &x, const double &val)
Independent (input) and dependent (output) variables for gradients.
fvar< T > log(const fvar< T > &x)
fvar< T > exp(const fvar< T > &x)