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