Stan  1.3
probability, sampling & optimization
 All Classes Namespaces Files Functions Variables Typedefs 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 
22  template <typename T1, typename T2>
23  inline typename boost::math::tools::promote_args<T1,T2>::type
24  log_sum_exp(const T2& a, const T1& b) {
25  using std::exp;
26  if (a > b)
27  return a + log1p(exp(b - a));
28  return b + log1p(exp(a - b));
29  }
30 
42  template <typename T>
43  T log_sum_exp(const std::vector<T>& x) {
44  using std::numeric_limits;
45  using std::log;
46  using std::exp;
47  T max = -numeric_limits<T>::infinity();
48  for (size_t ii = 0; ii < x.size(); ii++)
49  if (x[ii] > max)
50  max = x[ii];
51 
52  T sum = 0.0;
53  for (size_t ii = 0; ii < x.size(); ii++)
54  if (x[ii] != -numeric_limits<double>::infinity())
55  sum += exp(x[ii] - max);
56 
57  return max + log(sum);
58  }
59 
60 
61  }
62 }
63 
64 #endif

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