Stan Math Library  2.9.0
reverse mode automatic differentiation
log_sum_exp.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_FUN_LOG_SUM_EXP_HPP
2 #define STAN_MATH_PRIM_MAT_FUN_LOG_SUM_EXP_HPP
3 
6 #include <boost/math/tools/promotion.hpp>
7 #include <limits>
8 #include <vector>
9 
10 namespace stan {
11 
12  namespace math {
13 
27  template <int R, int C>
28  double log_sum_exp(const Eigen::Matrix<double, R, C>& x) {
29  using std::numeric_limits;
30  using std::log;
31  using std::exp;
32  double max = -numeric_limits<double>::infinity();
33  for (int i = 0; i < x.size(); i++)
34  if (x(i) > max)
35  max = x(i);
36 
37  double sum = 0.0;
38  for (int i = 0; i < x.size(); i++)
39  if (x(i) != -numeric_limits<double>::infinity())
40  sum += exp(x(i) - max);
41 
42  return max + log(sum);
43  }
44 
45  }
46 }
47 
48 #endif
fvar< T > sum(const std::vector< fvar< T > > &m)
Return the sum of the entries of the specified standard vector.
Definition: sum.hpp:20
fvar< T > log(const fvar< T > &x)
Definition: log.hpp:15
fvar< T > log_sum_exp(const std::vector< fvar< T > > &v)
Definition: log_sum_exp.hpp:14
fvar< T > exp(const fvar< T > &x)
Definition: exp.hpp:10
int max(const std::vector< int > &x)
Returns the maximum coefficient in the specified column vector.
Definition: max.hpp:21

     [ Stan Home Page ] © 2011–2015, Stan Development Team.