max_digits10.hpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. ///////////////////////////////////////////////////////////////
  2. // Copyright 2012 John Maddock. Distributed under the Boost
  3. // Software License, Version 1.0. (See accompanying file
  4. // LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt
  5. #ifndef BOOST_MATH_MAX_DIGITS10_HPP
  6. #define BOOST_MATH_MAX_DIGITS10_HPP
  7. namespace boost {
  8. namespace multiprecision {
  9. namespace detail {
  10. template <unsigned digits>
  11. struct calc_max_digits10
  12. {
  13. static constexpr unsigned max_digits_10(unsigned d)
  14. {
  15. //
  16. // We need ceil(log10(2) * d) + 1 decimal places to
  17. // guarantee round tripping, see: https://www.exploringbinary.com/number-of-digits-required-for-round-trip-conversions/
  18. // and references therein. Since log10(2) is irrational, then d*log10(2) will
  19. // never be exactly an integer so we can replace by trunc(log10(2) * d) + 2
  20. // and avoid the call to ceil:
  21. //
  22. return static_cast<unsigned>(0.301029995663981195213738894724493026768189881462108541310 * d) + 2;
  23. }
  24. static constexpr const unsigned value = max_digits_10(digits);
  25. };
  26. template <unsigned digits>
  27. struct calc_digits10
  28. {
  29. static constexpr unsigned digits_10(unsigned d)
  30. {
  31. //
  32. // We need floor(log10(2) * (d-1)), see:
  33. // https://www.exploringbinary.com/number-of-digits-required-for-round-trip-conversions/
  34. // and references therein.
  35. //
  36. return static_cast<unsigned>(0.301029995663981195213738894724493026768189881462108541310 * (d - 1));
  37. }
  38. static constexpr const unsigned value = digits_10(digits);
  39. };
  40. }}} // namespace boost::multiprecision::detail
  41. #endif