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__FUNCTIONS__LOG_SUM_EXP_HPP
2 #define STAN__MATH__FUNCTIONS__LOG_SUM_EXP_HPP
3 
5 #include <vector>
6 #include <boost/math/tools/promotion.hpp>
7 #include <limits>
8 
9 namespace stan {
10  namespace math {
11 
47  template <typename T1, typename T2>
48  inline typename boost::math::tools::promote_args<T1,T2>::type
49  log_sum_exp(const T2& a, const T1& b) {
50  using std::exp;
51  if (a > b)
52  return a + log1p_exp(b - a);
53  return b + log1p_exp(a - b);
54  }
55 
68  double log_sum_exp(const std::vector<double>& x) {
69  using std::numeric_limits;
70  using std::log;
71  using std::exp;
72  double max = -numeric_limits<double>::infinity();
73  for (size_t ii = 0; ii < x.size(); ii++)
74  if (x[ii] > max)
75  max = x[ii];
76 
77  double sum = 0.0;
78  for (size_t ii = 0; ii < x.size(); ii++)
79  if (x[ii] != -numeric_limits<double>::infinity())
80  sum += exp(x[ii] - max);
81 
82  return max + log(sum);
83  }
84 
85 
86  }
87 }
88 
89 #endif
boost::math::tools::promote_args< T >::type log1p_exp(const T a)
Calculates the log of 1 plus the exponential of the specified value without overflow.
Definition: log1p_exp.hpp:44
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.