frexp.hpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 <cmath>
  9. #include <limits>
  10. #include <type_traits>
  11. #include <boost/math/ccmath/isinf.hpp>
  12. #include <boost/math/ccmath/isnan.hpp>
  13. #include <boost/math/ccmath/isfinite.hpp>
  14. namespace boost::math::ccmath {
  15. namespace detail
  16. {
  17. template <typename Real>
  18. inline constexpr Real frexp_zero_impl(Real arg, int* exp)
  19. {
  20. *exp = 0;
  21. return arg;
  22. }
  23. template <typename Real>
  24. inline constexpr Real frexp_impl(Real arg, int* exp)
  25. {
  26. const bool negative_arg = (arg < Real(0));
  27. Real f = negative_arg ? -arg : arg;
  28. int e2 = 0;
  29. constexpr Real two_pow_32 = Real(4294967296);
  30. while (f >= two_pow_32)
  31. {
  32. f = f / two_pow_32;
  33. e2 += 32;
  34. }
  35. while(f >= Real(1))
  36. {
  37. f = f / Real(2);
  38. ++e2;
  39. }
  40. if(exp != nullptr)
  41. {
  42. *exp = e2;
  43. }
  44. return !negative_arg ? f : -f;
  45. }
  46. } // namespace detail
  47. template <typename Real, std::enable_if_t<!std::is_integral_v<Real>, bool> = true>
  48. inline constexpr Real frexp(Real arg, int* exp)
  49. {
  50. if(BOOST_MATH_IS_CONSTANT_EVALUATED(arg))
  51. {
  52. return arg == Real(0) ? detail::frexp_zero_impl(arg, exp) :
  53. arg == Real(-0) ? detail::frexp_zero_impl(arg, exp) :
  54. boost::math::ccmath::isinf(arg) ? detail::frexp_zero_impl(arg, exp) :
  55. boost::math::ccmath::isnan(arg) ? detail::frexp_zero_impl(arg, exp) :
  56. boost::math::ccmath::detail::frexp_impl(arg, exp);
  57. }
  58. else
  59. {
  60. using std::frexp;
  61. return frexp(arg, exp);
  62. }
  63. }
  64. template <typename Z, std::enable_if_t<std::is_integral_v<Z>, bool> = true>
  65. inline constexpr double frexp(Z arg, int* exp)
  66. {
  67. return boost::math::ccmath::frexp(static_cast<double>(arg), exp);
  68. }
  69. inline constexpr float frexpf(float arg, int* exp)
  70. {
  71. return boost::math::ccmath::frexp(arg, exp);
  72. }
  73. #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
  74. inline constexpr long double frexpl(long double arg, int* exp)
  75. {
  76. return boost::math::ccmath::frexp(arg, exp);
  77. }
  78. #endif
  79. }
  80. #endif // BOOST_MATH_CCMATH_FREXP_HPP