Stan Math Library  2.20.0
reverse mode automatic differentiation
log_sum_exp.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_ARR_FUN_LOG_SUM_EXP_HPP
2 #define STAN_MATH_PRIM_ARR_FUN_LOG_SUM_EXP_HPP
3 
5 #include <cmath>
6 #include <cstdlib>
7 #include <limits>
8 #include <vector>
9 
10 namespace stan {
11 namespace math {
12 
26 inline double log_sum_exp(const std::vector<double>& x) {
27  using std::exp;
28  using std::log;
29  using std::numeric_limits;
30  double max = -numeric_limits<double>::infinity();
31  for (double xx : x)
32  if (xx > max)
33  max = xx;
34 
35  double sum = 0.0;
36  for (size_t ii = 0; ii < x.size(); ii++)
37  if (x[ii] != -numeric_limits<double>::infinity())
38  sum += exp(x[ii] - max);
39 
40  return max + log(sum);
41 }
42 
43 } // namespace math
44 } // namespace stan
45 
46 #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:12
fvar< T > log_sum_exp(const std::vector< fvar< T > > &v)
Definition: log_sum_exp.hpp:12
fvar< T > exp(const fvar< T > &x)
Definition: exp.hpp:11
int max(const std::vector< int > &x)
Returns the maximum coefficient in the specified column vector.
Definition: max.hpp:21

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