dashu_float/math/cache.rs
1//! Opt-in cache of mathematical constants, enabling progressive refinement.
2
3use core::fmt;
4
5use dashu_base::{BitTest, EstimatedLog2, Sign, UnsignedAbs};
6use dashu_int::{IBig, UBig};
7
8use crate::error::assert_limited_precision;
9use crate::fbig::FBig;
10use crate::repr::{Context, Repr, Word};
11use crate::round::{Round, Rounded};
12use crate::utils::ceil_usize;
13
14/// Binary-splitting tree state — exact integers, losslessly extensible.
15///
16/// Represents `binary_split(start, num_terms)` as the universal triple
17/// `(P, Q, T)`, where `start` is 0 for π and 1 for `L(n)` (whose `k=0` term
18/// `1/n` is pulled out). These are pure integers: independent of base and
19/// rounding mode. To extend to `new_terms > num_terms`, compute the right half
20/// over the new range and merge with the universal `T' = T_l·Q_r + P_l·T_r`.
21#[derive(Clone)]
22pub(crate) struct CachedState {
23 pub p: UBig,
24 pub q: UBig,
25 pub t: IBig,
26 pub num_terms: usize,
27}
28
29/// An opt-in cache of mathematical constants.
30///
31/// Holds exact binary-splitting tree state so that repeated calls at increasing
32/// precision *extend* prior work instead of recomputing from scratch. For
33/// example, computing π at 100 digits and then at 1000 digits only pays for the
34/// extra ~900 digits of work.
35///
36/// The cache is **base-free**: a single [`ConstCache`] serves any base. The base
37/// and rounding mode are specified on each method call (e.g.
38/// `cache.pi::<10, HalfAway>(100)` for 100 decimal digits).
39///
40/// `ConstCache` is a plain struct of big integers, so it is `Send + Sync`. The
41/// methods take `&mut self` (they extend the cached state on a miss), so a caller
42/// either owns one directly, or — to share it across many values and operations —
43/// wraps it in `Rc<RefCell<ConstCache>>` as the
44/// [`CachedFBig`](crate::CachedFBig) type does. To share one cache across
45/// threads, wrap a `ConstCache` (or a `CachedFBig`) in `Arc<Mutex<..>>`.
46///
47/// # Examples
48///
49/// ```
50/// use dashu_float::ConstCache;
51/// use dashu_float::round::mode::HalfAway;
52///
53/// let mut cache = ConstCache::new();
54/// // first call computes from scratch
55/// let _pi_100 = cache.pi::<10, HalfAway>(100).value();
56/// // second call at higher precision extends the cached state
57/// let pi_1000 = cache.pi::<10, HalfAway>(1000).value();
58/// assert!(pi_1000.to_string().starts_with("3.141592653589793"));
59/// ```
60pub struct ConstCache {
61 pi: Option<CachedState>,
62 /// `L(6)`, `L(9)`, `L(99)` — the sub-series used by ln2 / ln10.
63 iacoth_6: Option<CachedState>,
64 iacoth_9: Option<CachedState>,
65 iacoth_99: Option<CachedState>,
66 /// Base-free integer `floor(sqrt(10005) · 2^sqrt_10005_bits)`, reused by π.
67 /// Unlike the series slots this holds a plain value (not a `(P,Q,T)` triple) and
68 /// is extended by a fresh Karatsuba `UBig::sqrt` — Newton refinement would be no
69 /// faster, since `UBig::sqrt` is already O(M(n)).
70 sqrt_10005: Option<UBig>,
71 sqrt_10005_bits: usize,
72}
73
74impl ConstCache {
75 /// Create an empty cache.
76 pub const fn new() -> Self {
77 Self {
78 pi: None,
79 iacoth_6: None,
80 iacoth_9: None,
81 iacoth_99: None,
82 sqrt_10005: None,
83 sqrt_10005_bits: 0,
84 }
85 }
86
87 /// `floor(sqrt(10005) · 2^bits)` as a base-free integer, cached and extended on
88 /// demand. Used by [`pi`](Self::pi). Computed via Karatsuba `UBig::sqrt` (O(M(n))).
89 /// Returns the value together with the number of bits it actually corresponds to
90 /// (which may be larger than requested, when a higher-precision value is reused).
91 fn sqrt_10005(&mut self, bits: usize) -> (UBig, usize) {
92 if bits > self.sqrt_10005_bits {
93 let n = UBig::from(10005u32) << (2 * bits);
94 self.sqrt_10005 = Some(dashu_base::SquareRoot::sqrt(&n));
95 self.sqrt_10005_bits = bits;
96 }
97 (self.sqrt_10005.as_ref().unwrap().clone(), self.sqrt_10005_bits)
98 }
99
100 /// π at `precision` base-`B` digits, rounded per `R`. Extends any prior π
101 /// state cached in `self`.
102 ///
103 /// # Panics
104 ///
105 /// Panics if `precision` is 0.
106 #[must_use]
107 pub fn pi<const B: Word, R: Round>(&mut self, precision: usize) -> Rounded<FBig<R, B>> {
108 assert_limited_precision(precision);
109
110 let bits = bits_for_precision::<B>(precision);
111 let num_terms = (bits * 100 / 4708) + 1;
112
113 let (_p, q, t) = extend_or_compute(&mut self.pi, 0, num_terms, chudnovsky_bs);
114
115 // Finalize: π = 426880·√10005·Q / T (identical to Context::pi)
116 let guard_bits = num_terms.bit_len() + 32;
117 let work_bits = bits + guard_bits;
118 let work_precision = precision_for_bits::<B>(work_bits);
119 let work = Context::<R>::new(work_precision);
120
121 // Finalize: π = 426880·√10005·Q / T. With √10005 ≈ isqrt_val·2^(-isqrt_bits)
122 // from the base-free cached isqrt, this folds into a single integer ratio
123 // π = (426880 · isqrt_val · Q) / (T · 2^isqrt_bits),
124 // avoiding any cross-base conversion of √10005 (convert_int is the fast path,
125 // the same one used for Q and T).
126 let (isqrt_val, isqrt_bits) = self.sqrt_10005(work_bits);
127 let num = IBig::from(426_880) * IBig::from(isqrt_val) * IBig::from(q);
128 let den = t << isqrt_bits;
129 let num_f = work.convert_int::<B>(num).value();
130 let den_f = work.convert_int::<B>(den).value();
131 let pi = num_f / den_f;
132 pi.with_precision(precision)
133 }
134
135 /// `L(n) = acoth(n)` at `precision` base-`B` digits, extending its cached
136 /// series state. Only `n ∈ {6, 9, 99}` are cached (the sub-series of ln2 / ln10).
137 fn iacoth<const N: u32, const B: Word, R: Round>(&mut self, precision: usize) -> FBig<R, B> {
138 // terms until r_k < B^{-p}: (2k+1)·log_B(n) > p. The count is generously
139 // over-provisioned (extra terms only add precision), so a plain (truncating)
140 // cast suffices in place of a ceiling.
141 let log_b_n = N.log2_est() / B.log2_est();
142 let required_terms = (precision as f32 / (2.0 * log_b_n)) as usize + 10;
143
144 let slot = match N {
145 6 => &mut self.iacoth_6,
146 9 => &mut self.iacoth_9,
147 99 => &mut self.iacoth_99,
148 _ => unreachable!("iacoth only caches n ∈ {{6, 9, 99}}"),
149 };
150 let (_p, q, t) = extend_or_compute(slot, 1, required_terms, |a, b| iacoth_bs(N, a, b));
151
152 // L(n) = (Q + T) / (n·Q)
153 let guard = ceil_usize(precision.log2_est() / B.log2_est()) + 2;
154 let work = Context::<R>::new(precision + guard);
155 let num = work.convert_int::<B>(q.as_ibig() + &t).value();
156 let denom = work.convert_int::<B>(IBig::from(N) * &q).value();
157 num / denom
158 }
159
160 /// ln(2) at `precision` base-`B` digits, reusing the cached `L(6)` and
161 /// `L(99)` sub-series.
162 ///
163 /// # Panics
164 ///
165 /// Panics if `precision` is 0.
166 #[must_use]
167 pub fn ln2<const B: Word, R: Round>(&mut self, precision: usize) -> FBig<R, B> {
168 // log(2) = 4·L(6) + 2·L(99) (Gourdon & Sebah, "Log 2")
169 let work = precision + combine_guard::<B>(precision);
170 let l6 = self.iacoth::<6, B, R>(work);
171 let l99 = self.iacoth::<99, B, R>(work);
172 (4u8 * l6 + 2u8 * l99).with_precision(precision).value()
173 }
174
175 /// ln(10) at `precision` base-`B` digits, reusing the cached `L(6)`, `L(99)`,
176 /// and `L(9)` sub-series.
177 ///
178 /// # Panics
179 ///
180 /// Panics if `precision` is 0.
181 #[must_use]
182 pub fn ln10<const B: Word, R: Round>(&mut self, precision: usize) -> FBig<R, B> {
183 // log(10) = 3·log(2) + 2·L(9) = 3·(4·L(6) + 2·L(99)) + 2·L(9)
184 // = 12·L(6) + 6·L(99) + 2·L(9)
185 // Flattening avoids the intermediate rounding of ln2 inside the product.
186 let work = precision + combine_guard::<B>(precision);
187 let l6 = self.iacoth::<6, B, R>(work);
188 let l99 = self.iacoth::<99, B, R>(work);
189 let l9 = self.iacoth::<9, B, R>(work);
190 (12u8 * l6 + 6u8 * l99 + 2u8 * l9)
191 .with_precision(precision)
192 .value()
193 }
194
195 /// ln(B) at `precision` base-`B` digits, reusing the cached ln2 / ln10 where
196 /// possible.
197 ///
198 /// # Panics
199 ///
200 /// Panics if `precision` is 0.
201 #[must_use]
202 pub fn ln_base<const B: Word, R: Round>(&mut self, precision: usize) -> FBig<R, B> {
203 match B {
204 2 => self.ln2::<B, R>(precision),
205 10 => self.ln10::<B, R>(precision),
206 b if b.is_power_of_two() => {
207 // ln(2^k) = k·ln(2); evaluate ln2 at elevated precision so the
208 // k·ln2 product survives the final round.
209 let work = precision + combine_guard::<B>(precision);
210 let bits = b.trailing_zeros() as usize;
211 (bits * self.ln2::<B, R>(work))
212 .with_precision(precision)
213 .value()
214 }
215 _ => {
216 // generic base: no cached L(n) sub-series applies, so compute ln(B) directly via
217 // the near-correct `ln_compute` (the cache only stores a near-correct constant — a
218 // cached value is re-rounded on read, and Ziv isn't needed here).
219 let ctx = Context::<R>::new(precision);
220 ctx.ln_compute::<B>(
221 &Repr::new(Repr::<B>::BASE.into(), 0),
222 // no cache for the generic base (its L(n) isn't cached)
223 precision,
224 false,
225 None,
226 )
227 .0
228 }
229 }
230 }
231
232 /// Sum of `num_terms` across all populated cache slots.
233 #[inline]
234 pub fn total_terms(&self) -> usize {
235 let sum = |s: &Option<CachedState>| s.as_ref().map_or(0, |s| s.num_terms);
236 sum(&self.pi) + sum(&self.iacoth_6) + sum(&self.iacoth_9) + sum(&self.iacoth_99)
237 }
238
239 /// Sum of word counts across all cached big integers (P, Q, T, and the cached
240 /// `√10005` isqrt).
241 ///
242 /// This reflects the underlying storage words used by the cached state.
243 #[inline]
244 pub fn total_words(&self) -> usize {
245 let slot_words = |s: &Option<CachedState>| {
246 s.as_ref().map_or(0, |s| {
247 s.p.as_words().len() + s.q.as_words().len() + s.t.as_sign_words().1.len()
248 })
249 };
250 slot_words(&self.pi)
251 + slot_words(&self.iacoth_6)
252 + slot_words(&self.iacoth_9)
253 + slot_words(&self.iacoth_99)
254 + self.sqrt_10005.as_ref().map_or(0, |s| s.as_words().len())
255 }
256
257 /// Clear all cached constant state, freeing the underlying memory.
258 ///
259 /// After calling `clear()`, the next constant computation will start from scratch
260 /// rather than extending the prior cached state.
261 #[inline]
262 pub fn clear(&mut self) {
263 self.pi = None;
264 self.iacoth_6 = None;
265 self.iacoth_9 = None;
266 self.iacoth_99 = None;
267 self.sqrt_10005 = None;
268 self.sqrt_10005_bits = 0;
269 }
270}
271
272impl Default for ConstCache {
273 #[inline]
274 fn default() -> Self {
275 Self::new()
276 }
277}
278
279/// Ensure `slot` holds state for at least `target` terms, then return `(P, Q, T)`
280/// covering `target` terms (or more, when an existing higher-precision state
281/// already covers `target` — finalize then rounds down to the requested precision).
282///
283/// `range_bs(a, b)` computes the leaf-merged state over `[a, b)` and must handle
284/// `a == b` by returning the identity `(1, 1, 0)`.
285fn extend_or_compute<F>(
286 slot: &mut Option<CachedState>,
287 start: usize,
288 target: usize,
289 range_bs: F,
290) -> (UBig, UBig, IBig)
291where
292 F: Fn(usize, usize) -> (UBig, UBig, IBig),
293{
294 match slot {
295 // Already have >= target terms: reuse (extra terms only add precision).
296 Some(s) if s.num_terms >= target => (s.p.clone(), s.q.clone(), s.t.clone()),
297 // Have fewer terms: extend the right half [num_terms, target) and merge.
298 Some(s) => {
299 let (pr, qr, tr) = range_bs(s.num_terms, target);
300 let (p, q, t) = merge(&s.p, &s.q, &s.t, &pr, &qr, &tr);
301 *slot = Some(CachedState {
302 p: p.clone(),
303 q: q.clone(),
304 t: t.clone(),
305 num_terms: target,
306 });
307 (p, q, t)
308 }
309 // Cold: compute from `start`.
310 None => {
311 let (p, q, t) = range_bs(start, target);
312 *slot = Some(CachedState {
313 p: p.clone(),
314 q: q.clone(),
315 t: t.clone(),
316 num_terms: target,
317 });
318 (p, q, t)
319 }
320 }
321}
322
323/// Reborrow an `Option<&mut ConstCache>` so it can be threaded into several
324/// sequential sub-calls. `as_deref_mut` is the natural reborrow here; clippy's
325/// `needless_option_as_deref` flags it (the deref target equals the referent),
326/// so the lint is allowed at this single centralized spot.
327#[inline]
328#[allow(clippy::needless_option_as_deref)]
329pub(crate) fn reborrow_cache<'a>(
330 cache: &'a mut Option<&mut ConstCache>,
331) -> Option<&'a mut ConstCache> {
332 cache.as_deref_mut()
333}
334
335/// Number of bits needed to represent `precision` base-`B` digits exactly.
336///
337/// For power-of-two bases this is exact; for arbitrary bases it uses the upper
338/// bound from [`EstimatedLog2`], which is far tighter than `ilog2(B) + 1`.
339fn bits_for_precision<const B: Word>(precision: usize) -> usize {
340 if B.is_power_of_two() {
341 precision.saturating_mul(B.ilog2() as usize)
342 } else {
343 // ub ≥ log2(B) with error ≤ 2/256. Multiply in f64 so the product
344 // is exact for precision up to 2^53. +1 guards float rounding.
345 let ub = B.log2_bounds().1;
346 ceil_usize(precision as f32 * ub) + 1
347 }
348}
349
350/// Convert a work-precision expressed in bits back to base-`B` digits.
351///
352/// For base 2 the identity holds; for power-of-two bases it uses ceiling
353/// division; for arbitrary bases it inverts the lower bound from
354/// [`EstimatedLog2`] to get a tight ceiling.
355fn precision_for_bits<const B: Word>(bits: usize) -> usize {
356 if B.is_power_of_two() {
357 let log2 = B.ilog2() as usize;
358 (bits + log2 - 1) / log2
359 } else {
360 // lb ≤ log2(B), so 1/lb ≥ 1/log2(B). +1 guards float rounding.
361 let lb = B.log2_bounds().0;
362 ceil_usize(bits as f32 / lb) + 1
363 }
364}
365
366/// Guard digits added when combining sub-series, large enough that the linear
367/// combination and its final round to `precision` are unaffected by summation
368/// rounding (a few digits cover the constant multipliers and term count).
369fn combine_guard<const B: Word>(precision: usize) -> usize {
370 ceil_usize(precision.log2_est() / B.log2_est()) + 4
371}
372
373/// Universal binary-splitting merge:
374/// `combine((P_l,Q_l,T_l), (P_r,Q_r,T_r)) = (P_l·P_r, Q_l·Q_r, T_l·Q_r + P_l·T_r)`.
375///
376/// This operation is associative, so the `(P, Q, T)` for a range is independent of
377/// how the recursion splits it — which is exactly what lets a cached partial tree
378/// state be extended by merging in a freshly computed right half.
379pub(crate) fn merge(
380 pl: &UBig,
381 ql: &UBig,
382 tl: &IBig,
383 pr: &UBig,
384 qr: &UBig,
385 tr: &IBig,
386) -> (UBig, UBig, IBig) {
387 let p = pl * pr;
388 let q = ql * qr;
389 // re-interpret the magnitudes as signed without cloning the big integers
390 let t = qr.as_ibig() * tl + pl.as_ibig() * tr;
391 (p, q, t)
392}
393
394/// Binary splitting implementation for the Chudnovsky series.
395/// Returns `(P, Q, T)` for the range `[a, b)`. An empty range `[a, a)` yields the
396/// identity `(1, 1, 0)`, so callers may safely merge a cached left state with a
397/// right half that starts exactly where the left one ended.
398pub(crate) fn chudnovsky_bs(a: usize, b: usize) -> (UBig, UBig, IBig) {
399 if a >= b {
400 return (UBig::ONE, UBig::ONE, IBig::ZERO);
401 }
402 if b - a == 1 {
403 const COEFF1: IBig = IBig::from_parts_const(Sign::Positive, 13591409);
404 const COEFF2: IBig = IBig::from_parts_const(Sign::Positive, 545140134);
405
406 // Base case: calculate single term
407 if a == 0 {
408 return (UBig::ONE, UBig::ONE, COEFF1);
409 }
410
411 let k = a as u64;
412 let p = UBig::from(6 * k - 5) * (2 * k - 1) * (6 * k - 1);
413 let q = UBig::from(k).pow(3) * 10_939_058_860_032_000u64;
414 let t_val = COEFF1 + COEFF2 * k;
415 let t_abs = &p * t_val.unsigned_abs();
416 let t = IBig::from(t_abs) * Sign::from(a % 2 == 1);
417 return (p, q, t);
418 }
419
420 // Recursive step
421 let mid = (a + b) / 2;
422 let (p_l, q_l, t_l) = chudnovsky_bs(a, mid);
423 let (p_r, q_r, t_r) = chudnovsky_bs(mid, b);
424
425 // T = T_L * Q_R + T_R * P_L (the universal merge)
426 merge(&p_l, &q_l, &t_l, &p_r, &q_r, &t_r)
427}
428
429/// Binary splitting for `L(n) = acoth(n) = Σ_{k≥0} 1/(n^{2k+1}(2k+1))` over `[1, b)`.
430///
431/// Term ratio (k≥1): `r_k/r_{k-1} = p_k/q_k` with `p_k = 2k-1`, `q_k = (2k+1)·n²`.
432/// The `k=0` term `r_0 = 1/n` is pulled out; over `[1, b)` the tree state satisfies
433/// `T/Q = n · Σ_{k=1}^{b-1} 1/((2k+1)·n^{2k+1})`, hence `L(n) = (Q + T)/(n·Q)`.
434///
435/// Using the ratio form (rather than independent `1/q_k` terms) keeps
436/// `Q = Π(2k+1)·n²` at O(p) digits: each leaf multiplies only small integers
437/// (with `n²` folded in), no `n.pow(2k+1)` per leaf.
438pub(crate) fn iacoth_bs(n: u32, a: usize, b: usize) -> (UBig, UBig, IBig) {
439 debug_assert!(a >= 1, "iacoth_bs leaf index must be >= 1");
440 if a >= b {
441 return (UBig::ONE, UBig::ONE, IBig::ZERO); // identity
442 }
443 // Precomputed initial block [1, 1+K): skip its K leaves on every fresh
444 // computation. Because the merge is associative, the constant triple is
445 // identical to the recursively computed state regardless of split order.
446 // It only applies at the series start (a == 1); recursive/extend calls have
447 // a >= 1 + K and never reach this branch.
448 if a == 1 {
449 if let Some((k, p0, q0, t0)) = iacoth_initial_block(n) {
450 // the precomputed block covers [1, 1+k); use it when [a, b) reaches
451 // past its end (b > k)
452 if b > k {
453 let (pr, qr, tr) = iacoth_bs(n, 1 + k, b);
454 return merge(&p0, &q0, &t0, &pr, &qr, &tr);
455 }
456 }
457 }
458 if b - a == 1 {
459 // leaf at k = a (a >= 1): (p_a, q_a, p_a), p_a = 2a-1, q_a = (2a+1)·n²
460 let pa = UBig::from(2 * a - 1);
461 let n2 = UBig::from(n).pow(2);
462 let qa = UBig::from(2 * a + 1) * n2;
463 let ta = IBig::from(pa.clone());
464 return (pa, qa, ta);
465 }
466 let mid = (a + b) / 2;
467 let (pl, ql, tl) = iacoth_bs(n, a, mid);
468 let (pr, qr, tr) = iacoth_bs(n, mid, b);
469 merge(&pl, &ql, &tl, &pr, &qr, &tr) // universal merge
470}
471
472/// Precomputed binary-splitting state for `L(n) = acoth(n)` over the first `K`
473/// terms `[1, 1+K)`, stored as `(K, P, Q, T)`. `K` is chosen (per `n`) so that
474/// `P`, `Q` and `|T|` each fit in a `u32`. Since `DoubleWord` is `u32`/`u64`/`u128`
475/// for `Word = u16`/`u32`/`u64`, a `u32`-sized literal is accepted by
476/// [`UBig::from_dword`] / [`IBig::from_parts_const`] on **every** configuration —
477/// so this single set of constants is portable without needing to detect the
478/// `Word` width (which is internal to `dashu-int`). The constants also use the
479/// inline small-integer representation, so instantiating them never allocates.
480///
481/// Only the sub-series that back ln2 / ln10 (`n ∈ {6, 9, 99}`) are precomputed;
482/// π cannot use this trick because its 2-term `T` already overflows a `u32`.
483fn iacoth_initial_block(n: u32) -> Option<(usize, UBig, UBig, IBig)> {
484 match n {
485 // L(6) over [1, 5): 4 leaves.
486 6 => Some(IACOTH_6_INITIAL),
487 // L(9) over [1, 4): 3 leaves.
488 9 => Some(IACOTH_9_INITIAL),
489 // L(99) over [1, 3): 2 leaves.
490 99 => Some(IACOTH_99_INITIAL),
491 _ => None,
492 }
493}
494
495/// `(K, P, Q, T)` for `L(6)` over `[1, 5)` (4 leaves).
496const IACOTH_6_INITIAL: (usize, UBig, UBig, IBig) = (
497 4,
498 UBig::from_word(105),
499 UBig::from_dword(1587237120),
500 IBig::from_parts_const(Sign::Positive, 14946549),
501);
502/// `(K, P, Q, T)` for `L(9)` over `[1, 4)` (3 leaves).
503const IACOTH_9_INITIAL: (usize, UBig, UBig, IBig) = (
504 3,
505 UBig::from_word(15),
506 UBig::from_dword(55801305),
507 IBig::from_parts_const(Sign::Positive, 231351),
508);
509/// `(K, P, Q, T)` for `L(99)` over `[1, 3)` (2 leaves).
510const IACOTH_99_INITIAL: (usize, UBig, UBig, IBig) = (
511 2,
512 UBig::from_word(3),
513 UBig::from_dword(1440894015),
514 IBig::from_parts_const(Sign::Positive, 49008),
515);
516
517/// Binary splitting for `e = Σ_{k≥0} 1/k!` over the index range `[a, b)` with `a ≥ 1`.
518///
519/// The `k = 0` term `1/0! = 1` is added by the caller. For `k ≥ 1` the term ratio
520/// is `tₖ/tₖ₋₁ = 1/k`, so each leaf is `(pₖ, qₖ, pₖ) = (1, k, 1)` and the universal
521/// [`merge`] applies verbatim (with `P ≡ 1`, it reduces to `T' = Tₗ·Qᵣ + Tᵣ`).
522/// Over `[1, N+1)` the triple satisfies `T/Q = Σ_{k=1}^{N} 1/k!`, hence the
523/// finalization `e = (Q + T)/Q` in [`compute_e`].
524///
525/// This is the optimal algorithm for *e*: there is no Chudnovsky-analog, and the
526/// factorial series with binary splitting is `O(M(n) log n)` — faster than π —
527/// beating both the AGM approach and `exp(1)` (which pays for argument reduction
528/// and `√p` powering that this series needs neither of).
529///
530/// An empty range yields the identity `(1, 1, 0)`.
531pub(crate) fn e_bs(a: usize, b: usize) -> (UBig, UBig, IBig) {
532 if a >= b {
533 return (UBig::ONE, UBig::ONE, IBig::ZERO);
534 }
535 if b - a == 1 {
536 // leaf at k = a (a ≥ 1): (pₖ, qₖ, pₖ) = (1, a, 1)
537 return (UBig::ONE, UBig::from(a), IBig::ONE);
538 }
539 let mid = (a + b) / 2;
540 let (pl, ql, tl) = e_bs(a, mid);
541 let (pr, qr, tr) = e_bs(mid, b);
542 merge(&pl, &ql, &tl, &pr, &qr, &tr) // universal merge
543}
544
545/// Number of series terms `N` for `e = Σ 1/k!` so that the truncation tail is
546/// safely below the target precision.
547///
548/// The tail after `k = N` is `Σ_{k>N} 1/k! < 2/(N+1)!`, so we need
549/// `log₂((N+1)!) > bits`. Stirling's lower bound `m! ≥ (m/e)ᵐ` gives
550/// `log₂(m!) ≥ m·(log₂ m − log₂ e)`; we seed `m` from the closed-form inverse of
551/// that bound and grow until it holds, so the result is always sufficient.
552/// Over-provisioning is harmless: extra terms only add precision, which the final
553/// `with_precision` discards.
554fn e_term_count(bits: usize) -> usize {
555 // `log2_bounds` (not `f64::log2`, which is std-only) keeps this `no_std`-clean;
556 // using its lower bound makes `lb` a valid lower bound on the Stirling LB, so the
557 // loop never terminates too early.
558 let target = (bits + 64) as f64; // margin for the tail's factor of 2 and final rounding
559 let log2_e = core::f64::consts::LOG2_E;
560 let lb = |m: usize| -> f64 { m as f64 * (m.log2_bounds().0 as f64 - log2_e) };
561 let denom = (bits.log2_bounds().1 as f64 - log2_e).max(1.0);
562 let mut m = (target / denom) as usize + 1;
563 while lb(m) < target {
564 m += 1;
565 }
566 // `m` corresponds to `N+1`; return `N`.
567 m.saturating_sub(1)
568}
569
570/// One-shot computation of *e* (Euler's number) at `precision` base-`B` digits,
571/// rounded per `R`.
572///
573/// Evaluates `e = Σ_{k=0}^∞ 1/k!` by exact-integer binary splitting (the
574/// [`e_bs`] kernel) and finalizes `e = (Q + T)/Q`. Unlike π, this is fully
575/// self-contained — it depends on no cached sub-constant and is reused by no
576/// other operation — so it deliberately does **not** live in [`ConstCache`] and is
577/// not progressively refined across calls. (See `Context::e` for the rationale.)
578pub(crate) fn compute_e<const B: Word, R: Round>(precision: usize) -> Rounded<FBig<R, B>> {
579 assert_limited_precision(precision);
580
581 let bits = bits_for_precision::<B>(precision);
582 let n = e_term_count(bits);
583 // Σ_{k=1}^{n} 1/k! = T/Q; the k=0 term 1/0! = 1 is folded in as (Q + T)/Q.
584 let (_p, q, t) = e_bs(1, n + 1);
585
586 // Evaluate (Q + T)/Q at an elevated working precision so the integer→float
587 // conversion and the division round correctly down to `precision`. The guard
588 // mirrors `ConstCache::pi`: a few bits for the term count, plus a fixed margin.
589 let guard_bits = n.bit_len() + 32;
590 let work_precision = precision_for_bits::<B>(bits + guard_bits);
591 let work = Context::<R>::new(work_precision);
592 let num = work.convert_int::<B>(q.as_ibig() + &t).value();
593 let den = work.convert_int::<B>(IBig::from(q)).value();
594 let e = num / den;
595 e.with_precision(precision)
596}
597
598impl fmt::Debug for ConstCache {
599 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
600 f.debug_struct("ConstCache")
601 .field("pi", &DebugSlot(&self.pi))
602 .field("iacoth_6", &DebugSlot(&self.iacoth_6))
603 .field("iacoth_9", &DebugSlot(&self.iacoth_9))
604 .field("iacoth_99", &DebugSlot(&self.iacoth_99))
605 .finish()
606 }
607}
608
609/// Newtype so we can implement `Debug` for `&Option<CachedState>` via the
610/// big-integer `Debug` formatters.
611struct DebugSlot<'a>(&'a Option<CachedState>);
612
613impl fmt::Debug for DebugSlot<'_> {
614 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
615 match self.0 {
616 Some(s) => f
617 .debug_struct("CachedState")
618 .field("num_terms", &s.num_terms)
619 .field("p", &s.p)
620 .field("q", &s.q)
621 .field("t", &s.t)
622 .finish(),
623 None => f.write_str("None"),
624 }
625 }
626}
627
628#[cfg(test)]
629mod tests {
630 use super::*;
631 use crate::round::mode;
632 use crate::DBig;
633 use alloc::format;
634 use alloc::string::ToString; // not in the prelude under no_std
635
636 /// Independently (left-fold) merge the first `k` leaves of `L(n)` and check
637 /// that the result matches the precomputed constant triple. Guards against
638 /// transcription errors in the `IACOTH_*_INITIAL` literals; correctness of the
639 /// finalized `L(n)` values is covered by `log::tests`.
640 #[test]
641 fn test_iacoth_initial_blocks() {
642 fn check(n: u32, expected: &(usize, UBig, UBig, IBig)) {
643 let k = expected.0;
644 // independently (left-fold) merge the first k leaves
645 let mut acc = (UBig::ONE, UBig::ONE, IBig::ZERO);
646 for kk in 1..=k {
647 let pa = UBig::from(2 * kk as u64 - 1);
648 let qa = UBig::from(2 * kk as u64 + 1) * UBig::from(n).pow(2);
649 let ta = IBig::from(pa.clone());
650 let (p, q, t) = merge(&acc.0, &acc.1, &acc.2, &pa, &qa, &ta);
651 acc = (p, q, t);
652 }
653 assert_eq!(acc.0, expected.1, "P mismatch for n={n}");
654 assert_eq!(acc.1, expected.2, "Q mismatch for n={n}");
655 assert_eq!(acc.2, expected.3, "T mismatch for n={n}");
656 // the seed branch must reproduce the same state as the full recursion
657 assert_eq!(iacoth_bs(n, 1, 1 + k), (acc.0, acc.1, acc.2));
658 }
659 check(6, &IACOTH_6_INITIAL);
660 check(9, &IACOTH_9_INITIAL);
661 check(99, &IACOTH_99_INITIAL);
662 }
663
664 #[test]
665 fn test_pi_matches_context() {
666 // Cache miss must reproduce Context::pi exactly.
667 for &precision in &[10usize, 50, 100] {
668 let mut cache = ConstCache::new();
669 let cached = cache.pi::<10, mode::HalfEven>(precision).value();
670 let direct = Context::<mode::HalfEven>::new(precision)
671 .pi::<10>(None)
672 .value();
673 assert_eq!(cached, direct, "pi mismatch at precision {precision}");
674 }
675 }
676
677 #[test]
678 fn test_pi_lower_precision_reuses() {
679 // Compute at high precision, then a lower-precision request must round
680 // down from the cached state and still be correct.
681 let mut cache = ConstCache::new();
682 let _pi_high = cache.pi::<10, mode::HalfEven>(200).value();
683 // the slot now holds >=200 terms; a 50-digit request reuses it
684 let pi_50 = cache.pi::<10, mode::HalfEven>(50).value();
685 let direct = Context::<mode::HalfEven>::new(50).pi::<10>(None).value();
686 assert_eq!(pi_50, direct);
687 }
688
689 #[test]
690 fn test_pi_extension_matches_scratch() {
691 // Extending 100 -> 1000 must be bit-identical to a from-scratch 1000-digit compute.
692 let mut cache = ConstCache::new();
693 let _pi_100 = cache.pi::<10, mode::HalfAway>(100).value();
694 let pi_1000_extended = cache.pi::<10, mode::HalfAway>(1000).value();
695
696 let direct = Context::<mode::HalfAway>::new(1000).pi::<10>(None).value();
697 assert_eq!(pi_1000_extended, direct);
698 }
699
700 #[test]
701 fn test_iacoth_matches_context() {
702 let mut cache = ConstCache::new();
703 // ln2 / ln10 via cache must match ln(2)/ln(10) computed independently
704 // through Context::ln (a different, atanh-based algorithm) at several precisions.
705 for &precision in &[20usize, 45, 80] {
706 let cached_ln2 = cache
707 .ln2::<10, mode::Zero>(precision)
708 .with_precision(precision)
709 .value();
710 let ln2_ctx = Context::<mode::Zero>::new(precision);
711 let direct_ln2 = ln2_ctx.unwrap_fp(ln2_ctx.ln::<10>(&Repr::new(2.into(), 0), None));
712 assert_eq!(cached_ln2, direct_ln2, "ln2 mismatch at precision {precision}");
713
714 let cached_ln10 = cache
715 .ln10::<10, mode::Zero>(precision)
716 .with_precision(precision)
717 .value();
718 let ln10_ctx = Context::<mode::Zero>::new(precision);
719 let direct_ln10 = ln10_ctx.unwrap_fp(ln10_ctx.ln::<10>(&Repr::new(10.into(), 0), None));
720 assert_eq!(cached_ln10, direct_ln10, "ln10 mismatch at precision {precision}");
721 }
722 }
723
724 #[test]
725 fn test_iacoth_extension_matches_scratch() {
726 // Extend ln2 from low to high precision; result must match from-scratch.
727 let mut cache = ConstCache::new();
728 let _ln2_low = cache.ln2::<10, mode::HalfAway>(20);
729 let ln2_high = cache.ln2::<10, mode::HalfAway>(120);
730
731 let mut fresh = ConstCache::new();
732 let direct = fresh.ln2::<10, mode::HalfAway>(120);
733 assert_eq!(ln2_high, direct);
734 }
735
736 #[test]
737 fn test_ln_base() {
738 // binary base: ln(base) == ln(2)
739 let mut cache = ConstCache::new();
740 let ln_base = cache.ln_base::<2, mode::HalfAway>(50);
741 let ln2 = cache.ln2::<2, mode::HalfAway>(50);
742 assert_eq!(ln_base, ln2);
743
744 // power-of-two base: ln(8) = 3·ln(2)
745 let ln8 = cache.ln_base::<8, mode::HalfAway>(50);
746 let expected = 3u8 * cache.ln2::<8, mode::HalfAway>(50);
747 assert_eq!(ln8.with_precision(50).value(), expected.with_precision(50).value());
748 }
749
750 #[test]
751 fn test_debug_shows_bigint_head_tail() {
752 let mut cache = ConstCache::new();
753 let _pi = cache.pi::<10, mode::HalfAway>(100); // populate the cache (value unused)
754 let s = format!("{:?}", cache);
755 assert!(s.contains("pi"));
756 assert!(s.contains("num_terms"));
757 // UBig/IBig Debug prints head..tail, so the output stays compact
758 assert!(s.contains(".."), "Debug output should use head..tail truncation");
759 assert!(s.len() < 512);
760 }
761
762 #[test]
763 fn test_sqrt_10005_cached_and_counted() {
764 // Computing π caches the base-free √10005 isqrt; total_words counts it, and
765 // clear() frees it.
766 let mut cache = ConstCache::new();
767 assert_eq!(cache.total_terms(), 0);
768 assert_eq!(cache.total_words(), 0);
769
770 let _pi = cache.pi::<10, mode::HalfAway>(200); // fills the cache (value unused)
771 // the isqrt is now cached (total_terms stays series-only; words include isqrt)
772 assert!(cache.total_words() > 0);
773
774 cache.clear();
775 assert_eq!(cache.total_terms(), 0);
776 assert_eq!(cache.total_words(), 0);
777
778 // after clear, π recomputes from scratch and still matches the direct value
779 let direct = Context::<mode::HalfAway>::new(50).pi::<10>(None).value();
780 let after_clear = cache.pi::<10, mode::HalfAway>(50).value();
781 assert_eq!(after_clear, direct);
782 }
783
784 #[test]
785 fn test_sqrt_10005_reuse_higher_precision() {
786 // A high-precision π call caches a high-bit isqrt; a later lower-precision
787 // call must reuse it (no recompute) and still be correct.
788 let mut cache = ConstCache::new();
789 let _high = cache.pi::<2, mode::HalfEven>(1000);
790 let words_after_high = cache.total_words();
791
792 let low = cache.pi::<2, mode::HalfEven>(100).value();
793 // word count unchanged ⇒ isqrt (and series) were reused, not recomputed
794 assert_eq!(cache.total_words(), words_after_high);
795
796 let direct = Context::<mode::HalfEven>::new(100).pi::<2>(None).value();
797 assert_eq!(low, direct);
798 }
799
800 /// `e_bs(1, N+1)` produces `(P, Q, T)` with `T/Q = Σ_{k=1}^{N} 1/k!` and `P ≡ 1`.
801 #[test]
802 fn test_e_bs_partial_sums() {
803 // N=1: 1/1! = 1 → (1, 1, 1)
804 let (p, q, t) = e_bs(1, 2);
805 assert_eq!(p, UBig::ONE);
806 assert_eq!(q, UBig::from(1u32));
807 assert_eq!(t, IBig::from(1));
808
809 // N=3: 1 + 1/2 + 1/6 = 10/6 → (1, 6, 10)
810 let (p, q, t) = e_bs(1, 4);
811 assert_eq!(p, UBig::ONE);
812 assert_eq!(q, UBig::from(6u32));
813 assert_eq!(t, IBig::from(10));
814
815 // N=4: +1/24 → 41/24 → (1, 24, 41)
816 let (p, q, t) = e_bs(1, 5);
817 assert_eq!(p, UBig::ONE);
818 assert_eq!(q, UBig::from(24u32));
819 assert_eq!(t, IBig::from(41));
820
821 // empty range is the identity triple
822 let (p, q, t) = e_bs(7, 7);
823 assert_eq!(p, UBig::ONE);
824 assert_eq!(q, UBig::ONE);
825 assert_eq!(t, IBig::ZERO);
826 }
827
828 /// `compute_e` (factorial binary splitting) and `exp(1)` (argument reduction,
829 /// Taylor series, and powering) are two independent algorithms for the same
830 /// value, so both must yield the identical correctly-rounded result.
831 #[test]
832 fn test_e_matches_exp_one() {
833 fn check<const B: Word>(p: usize) {
834 let ctx = Context::<mode::HalfAway>::new(p);
835 let e_const = ctx.e::<B>().value();
836 let exp_one = ctx
837 .exp::<B>(&Repr::<B>::new(IBig::from(1), 0), None)
838 .unwrap()
839 .value();
840 assert_eq!(e_const, exp_one, "e != exp(1) at precision {p}, base {B}");
841 }
842 for &p in &[1usize, 2, 5, 13, 50, 137, 500] {
843 check::<10>(p);
844 check::<2>(p);
845 }
846 }
847
848 /// Ground-truth prefix of e (OEIS A001113), independent of the `exp` path.
849 /// The 45-decimal prefix is far from the precision-100 rounding boundary.
850 #[test]
851 fn test_e_known_decimal_prefix() {
852 // e = 2.71828182845904523536028747135266249775724709369995957…
853 let s = DBig::e(100).to_string();
854 assert!(s.starts_with("2.718281828459045235360287471352662497757247093699"), "got {s}");
855 // sanity: e is in (2, 3)
856 let e = DBig::e(10);
857 assert!(e > DBig::from(2u32));
858 assert!(e < DBig::from(3u32));
859 }
860
861 /// `e_term_count` must return enough terms that Stirling's lower bound on
862 /// `(N+1)!` actually exceeds the target bit count.
863 #[test]
864 fn test_e_term_count_sufficient() {
865 for &bits in &[1usize, 10, 100, 1000, 10_000, 100_000] {
866 let n = e_term_count(bits);
867 let m = (n + 1) as f64;
868 let stirling_lb = m * (m.log2() - core::f64::consts::LOG2_E);
869 assert!(stirling_lb > bits as f64, "N={n} insufficient for bits={bits}");
870 }
871 }
872}