1 // (C) Copyright Nick Thompson 2020.
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)
6 #ifndef BOOST_MATH_TOOLS_ENGEL_EXPANSION_HPP
7 #define BOOST_MATH_TOOLS_ENGEL_EXPANSION_HPP
16 namespace boost::math::tools {
18 template<typename Real, typename Z = int64_t>
19 class engel_expansion {
21 engel_expansion(Real x) : x_{x}
29 throw std::domain_error("Cannot convert non-finites into an Engel expansion.");
34 throw std::domain_error("Zero does not have an Engel expansion.");
37 // Let the error bound grow by 1 ULP/iteration.
38 // I haven't done the error analysis to show that this is an expected rate of error growth,
39 // but if you don't do this, you can easily get into an infinite loop.
43 Real scale = std::numeric_limits<Real>::epsilon()*abs(x_)/2;
45 while (abs(x_ - computed) > (i++)*scale)
48 Real ak = ceil(recip);
49 a_.push_back(static_cast<Z>(ak));
59 for (size_t i = 1; i < a_.size(); ++i)
61 // Sanity check: This should only happen when wraparound occurs:
64 throw std::domain_error("The digits of an Engel expansion must form a non-decreasing sequence; consider increasing the wide of the integer type.");
66 // Watch out for saturating behavior:
67 if (a_[i] == std::numeric_limits<Z>::max())
69 throw std::domain_error("The integer type Z does not have enough width to hold the terms of the Engel expansion; please widen the type.");
76 const std::vector<Z>& digits() const
81 template<typename T, typename Z2>
82 friend std::ostream& operator<<(std::ostream& out, engel_expansion<T, Z2>& eng);
90 template<typename Real, typename Z2>
91 std::ostream& operator<<(std::ostream& out, engel_expansion<Real, Z2>& engel)
93 constexpr const int p = std::numeric_limits<Real>::max_digits10;
94 if constexpr (p == 2147483647)
96 out << std::setprecision(engel.x_.backend().precision());
100 out << std::setprecision(p);
104 for (size_t i = 0; i < engel.a_.size() - 1; ++i)
106 out << engel.a_[i] << ", ";
108 out << engel.a_.back();