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_LUROTH_EXPANSION_HPP
7 #define BOOST_MATH_TOOLS_LUROTH_EXPANSION_HPP
16 namespace boost::math::tools {
18 template<typename Real, typename Z = int64_t>
19 class luroth_expansion {
21 luroth_expansion(Real x) : x_{x}
29 throw std::domain_error("Cannot convert non-finites into a Luroth representation.");
33 d_.push_back(static_cast<Z>(dn1));
39 // This attempts to follow the notation of:
40 // "Khinchine's constant for Luroth Representation", by Sophia Kalpazidou.
44 // Let the error bound grow by 1 ULP/iteration.
45 // I haven't done the error analysis to show that this is an expected rate of error growth,
46 // but if you don't do this, you can easily get into an infinite loop.
48 Real scale = std::numeric_limits<Real>::epsilon()*abs(x_)/2;
49 while (abs(x_ - computed) > (i++)*scale)
52 Real dn = floor(recip);
53 // x = n + 1/k => lur(x) = ((n; k - 1))
54 // Note that this is a bit different than Kalpazidou (examine the half-open interval of definition carefully).
55 // One way to examine this definition is better for rationals (it never happens for irrationals)
56 // is to consider i + 1/3. If you follow Kalpazidou, then you get ((i, 3, 0)); a zero digit!
57 // That's bad since it destroys uniqueness and also breaks the computation of the geometric mean.
59 d_.push_back(static_cast<Z>(dn - 1));
62 d_.push_back(static_cast<Z>(dn));
66 x = dn*(dn+1)*(x - tmp);
69 for (size_t i = 1; i < d_.size(); ++i)
74 throw std::domain_error("Found a digit <= 0; this is an error.");
81 const std::vector<Z>& digits() const {
85 // Under the assumption of 'randomness', this mean converges to 2.2001610580.
86 // See Finch, Mathematical Constants, section 1.8.1.
87 Real digit_geometric_mean() const {
89 return std::numeric_limits<Real>::quiet_NaN();
94 for (size_t i = 1; i < d_.size(); ++i) {
95 g += log(static_cast<Real>(d_[i]));
97 return exp(g/(d_.size() - 1));
100 template<typename T, typename Z2>
101 friend std::ostream& operator<<(std::ostream& out, luroth_expansion<T, Z2>& scf);
109 template<typename Real, typename Z2>
110 std::ostream& operator<<(std::ostream& out, luroth_expansion<Real, Z2>& luroth)
112 constexpr const int p = std::numeric_limits<Real>::max_digits10;
113 if constexpr (p == 2147483647)
115 out << std::setprecision(luroth.x_.backend().precision());
119 out << std::setprecision(p);
122 out << "((" << luroth.d_.front();
123 if (luroth.d_.size() > 1)
126 for (size_t i = 1; i < luroth.d_.size() -1; ++i)
128 out << luroth.d_[i] << ", ";
130 out << luroth.d_.back();