frexp.hpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // (C) Copyright Christopher Kormanyos 1999 - 2021.
  2. // (C) Copyright Matt Borland 2021.
  3. // Use, modification and distribution are subject to the
  4. // Boost Software License, Version 1.0. (See accompanying file
  5. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. #ifndef BOOST_MATH_CCMATH_FREXP_HPP
  7. #define BOOST_MATH_CCMATH_FREXP_HPP
  8. #include <boost/math/ccmath/detail/config.hpp>
  9. #ifdef BOOST_MATH_NO_CCMATH
  10. #error "The header <boost/math/frexp.hpp> can only be used in C++17 and later."
  11. #endif
  12. #include <boost/math/ccmath/isinf.hpp>
  13. #include <boost/math/ccmath/isnan.hpp>
  14. #include <boost/math/ccmath/isfinite.hpp>
  15. namespace boost::math::ccmath {
  16. namespace detail
  17. {
  18. template <typename Real>
  19. inline constexpr Real frexp_zero_impl(Real arg, int* exp)
  20. {
  21. *exp = 0;
  22. return arg;
  23. }
  24. template <typename Real>
  25. inline constexpr Real frexp_impl(Real arg, int* exp)
  26. {
  27. const bool negative_arg = (arg < Real(0));
  28. Real f = negative_arg ? -arg : arg;
  29. int e2 = 0;
  30. constexpr Real two_pow_32 = Real(4294967296);
  31. while (f >= two_pow_32)
  32. {
  33. f = f / two_pow_32;
  34. e2 += 32;
  35. }
  36. while(f >= Real(1))
  37. {
  38. f = f / Real(2);
  39. ++e2;
  40. }
  41. if(exp != nullptr)
  42. {
  43. *exp = e2;
  44. }
  45. return !negative_arg ? f : -f;
  46. }
  47. } // namespace detail
  48. template <typename Real, std::enable_if_t<!std::is_integral_v<Real>, bool> = true>
  49. inline constexpr Real frexp(Real arg, int* exp)
  50. {
  51. if(BOOST_MATH_IS_CONSTANT_EVALUATED(arg))
  52. {
  53. return arg == Real(0) ? detail::frexp_zero_impl(arg, exp) :
  54. arg == Real(-0) ? detail::frexp_zero_impl(arg, exp) :
  55. boost::math::ccmath::isinf(arg) ? detail::frexp_zero_impl(arg, exp) :
  56. boost::math::ccmath::isnan(arg) ? detail::frexp_zero_impl(arg, exp) :
  57. boost::math::ccmath::detail::frexp_impl(arg, exp);
  58. }
  59. else
  60. {
  61. using std::frexp;
  62. return frexp(arg, exp);
  63. }
  64. }
  65. template <typename Z, std::enable_if_t<std::is_integral_v<Z>, bool> = true>
  66. inline constexpr double frexp(Z arg, int* exp)
  67. {
  68. return boost::math::ccmath::frexp(static_cast<double>(arg), exp);
  69. }
  70. inline constexpr float frexpf(float arg, int* exp)
  71. {
  72. return boost::math::ccmath::frexp(arg, exp);
  73. }
  74. #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
  75. inline constexpr long double frexpl(long double arg, int* exp)
  76. {
  77. return boost::math::ccmath::frexp(arg, exp);
  78. }
  79. #endif
  80. }
  81. #endif // BOOST_MATH_CCMATH_FREXP_HPP