logaddexp.hpp 915 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // (C) Copyright Matt Borland 2022.
  2. // Use, modification and distribution are subject to the
  3. // Boost Software License, Version 1.0. (See accompanying file
  4. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. #include <cmath>
  6. #include <limits>
  7. #include <boost/math/special_functions/fpclassify.hpp>
  8. #include <boost/math/constants/constants.hpp>
  9. namespace boost { namespace math {
  10. // Calculates log(exp(x1) + exp(x2))
  11. template <typename Real>
  12. Real logaddexp(Real x1, Real x2) noexcept
  13. {
  14. using std::log1p;
  15. using std::exp;
  16. using std::abs;
  17. // Validate inputs first
  18. if (!(boost::math::isfinite)(x1))
  19. {
  20. return x1;
  21. }
  22. else if (!(boost::math::isfinite)(x2))
  23. {
  24. return x2;
  25. }
  26. const Real temp = x1 - x2;
  27. if (temp > 0)
  28. {
  29. return x1 + log1p(exp(-temp));
  30. }
  31. return x2 + log1p(exp(temp));
  32. }
  33. }} // Namespace boost::math