Stan Math Library  2.15.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  namespace math {
12 
26  template <int R, int C>
27  double log_sum_exp(const Eigen::Matrix<double, R, C>& x) {
28  using std::numeric_limits;
29  using std::log;
30  using std::exp;
31  double max = -numeric_limits<double>::infinity();
32  for (int i = 0; i < x.size(); i++)
33  if (x(i) > max)
34  max = x(i);
35 
36  double sum = 0.0;
37  for (int i = 0; i < x.size(); i++)
38  if (x(i) != -numeric_limits<double>::infinity())
39  sum += exp(x(i) - max);
40 
41  return max + log(sum);
42  }
43 
44  }
45 }
46 
47 #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:14
fvar< T > log_sum_exp(const std::vector< fvar< T > > &v)
Definition: log_sum_exp.hpp:13
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:22

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