// (C) Copyright Matt Borland 2022. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include #include #include #include #include #include #include namespace boost { namespace math { // https://nhigham.com/2021/01/05/what-is-the-log-sum-exp-function/ // See equation (#) template ::value_type> Real logsumexp(ForwardIterator first, ForwardIterator last) { using std::exp; using std::log1p; const auto elem = std::max_element(first, last); const Real max_val = *elem; Real arg = 0; while (first != last) { if (first != elem) { arg += exp(*first - max_val); } ++first; } return max_val + log1p(arg); } template inline Real logsumexp(const Container& c) { return logsumexp(std::begin(c), std::end(c)); } template ::type, typename std::enable_if::value, bool>::type = true> inline Real logsumexp(Args&& ...args) { std::initializer_list list {std::forward(args)...}; if(list.size() == 2) { return logaddexp(*list.begin(), *std::next(list.begin())); } return logsumexp(list.begin(), list.end()); } }} // Namespace boost::math