logb.hpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // (C) Copyright Matt Borland 2021.
  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. #ifndef BOOST_MATH_CCMATH_LOGB_HPP
  6. #define BOOST_MATH_CCMATH_LOGB_HPP
  7. #include <boost/math/ccmath/detail/config.hpp>
  8. #ifdef BOOST_MATH_NO_CCMATH
  9. #error "The header <boost/math/logb.hpp> can only be used in C++17 and later."
  10. #endif
  11. #include <boost/math/ccmath/frexp.hpp>
  12. #include <boost/math/ccmath/isinf.hpp>
  13. #include <boost/math/ccmath/isnan.hpp>
  14. #include <boost/math/ccmath/abs.hpp>
  15. namespace boost::math::ccmath {
  16. namespace detail {
  17. // The value of the exponent returned by std::logb is always 1 less than the exponent returned by
  18. // std::frexp because of the different normalization requirements: for the exponent e returned by std::logb,
  19. // |arg*r^-e| is between 1 and r (typically between 1 and 2), but for the exponent e returned by std::frexp,
  20. // |arg*2^-e| is between 0.5 and 1.
  21. template <typename T>
  22. constexpr T logb_impl(T arg) noexcept
  23. {
  24. int exp = 0;
  25. boost::math::ccmath::frexp(arg, &exp);
  26. return static_cast<T>(exp - 1);
  27. }
  28. } // Namespace detail
  29. template <typename Real, std::enable_if_t<!std::is_integral_v<Real>, bool> = true>
  30. constexpr Real logb(Real arg) noexcept
  31. {
  32. if(BOOST_MATH_IS_CONSTANT_EVALUATED(arg))
  33. {
  34. if (boost::math::ccmath::abs(arg) == Real(0))
  35. {
  36. return -std::numeric_limits<Real>::infinity();
  37. }
  38. else if (boost::math::ccmath::isinf(arg))
  39. {
  40. return std::numeric_limits<Real>::infinity();
  41. }
  42. else if (boost::math::ccmath::isnan(arg))
  43. {
  44. return arg;
  45. }
  46. return boost::math::ccmath::detail::logb_impl(arg);
  47. }
  48. else
  49. {
  50. using std::logb;
  51. return logb(arg);
  52. }
  53. }
  54. template <typename Z, std::enable_if_t<std::is_integral_v<Z>, bool> = true>
  55. constexpr double logb(Z arg) noexcept
  56. {
  57. return boost::math::ccmath::logb(static_cast<double>(arg));
  58. }
  59. constexpr float logbf(float arg) noexcept
  60. {
  61. return boost::math::ccmath::logb(arg);
  62. }
  63. #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
  64. constexpr long double logbl(long double arg) noexcept
  65. {
  66. return boost::math::ccmath::logb(arg);
  67. }
  68. #endif
  69. } // Namespaces
  70. #endif // BOOST_MATH_CCMATH_LOGB_HPP