Stan  2.5.0
probability, sampling & optimization
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
log_sum_exp.hpp
Go to the documentation of this file.
1 #ifndef STAN__MATH__MATRIX__LOG_SUM_EXP_HPP
2 #define STAN__MATH__MATRIX__LOG_SUM_EXP_HPP
3 
4 #include <limits>
5 #include <vector>
6 #include <boost/math/tools/promotion.hpp>
9 
10 
11 namespace stan {
12 
13  namespace math {
14 
28  template <int R, int C>
29  double log_sum_exp(const Eigen::Matrix<double,R,C>& x) {
30  using std::numeric_limits;
31  using std::log;
32  using std::exp;
33  double max = -numeric_limits<double>::infinity();
34  for (int i = 0; i < x.size(); i++)
35  if (x(i) > max)
36  max = x(i);
37 
38  double sum = 0.0;
39  for (int i = 0; i < x.size(); i++)
40  if (x(i) != -numeric_limits<double>::infinity())
41  sum += exp(x(i) - max);
42 
43  return max + log(sum);
44  }
45 
46  }
47 }
48 
49 #endif
boost::math::tools::promote_args< T1, T2 >::type log_sum_exp(const T2 &a, const T1 &b)
Calculates the log sum of exponetials without overflow.
Definition: log_sum_exp.hpp:49
Eigen::Matrix< T, Rows, Cols > exp(const Eigen::Matrix< T, Rows, Cols > &m)
Return the element-wise exponentiation of the matrix or vector.
Definition: exp.hpp:18
double max(const double a, const double b)
Definition: max.hpp:7
Eigen::Matrix< T, Rows, Cols > log(const Eigen::Matrix< T, Rows, Cols > &m)
Return the element-wise logarithm of the matrix or vector.
Definition: log.hpp:16
double sum(std::vector< double > &x)
Definition: sum.hpp:10
fvar< T > log(const fvar< T > &x)
Definition: log.hpp:15
fvar< T > exp(const fvar< T > &x)
Definition: exp.hpp:16

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