Skip to main content

dashu_float/
exp.rs

1use core::cmp::Ordering;
2use core::convert::TryInto;
3
4use crate::{
5    ball::{ulps, Ball},
6    error::{assert_finite, assert_limited_precision, FpError, FpResult},
7    fbig::FBig,
8    math::cache::{reborrow_cache, ConstCache},
9    repr::{Context, Repr, Word},
10    round::{mode, ErrorBounds, Round, Rounded, Rounding::*},
11};
12use dashu_base::{Approximation::*, BitTest, DivRemEuclid, EstimatedLog2, Sign};
13use dashu_int::{IBig, UBig};
14
15// `|x|` (in log2) above which exp's reduction quotient `s = floor(x/ln B)` might overflow `isize`,
16// so the hoisted overflow probe must run instead of the fast skip. `s` overflows when
17// `|x| > isize::MAX · ln B`, i.e. `log2|x| > log2(isize::MAX) + log2(ln B)`; the minimum (over
18// `B ≥ 2`) is `~isize::BITS − 1.5`, and the `−3` margin stays below it. The literal was `61` (the
19// 64-bit value); on 32-bit `isize` it must be ~29 or `exp_compute`'s `s.try_into().expect()` panics
20// for inputs like `exp(-2⁵⁰)` (whose `s ≈ -1.8e15` overflows 32-bit `isize`).
21const EXP_OVERFLOW_PROBE_LOG2: f32 = (isize::BITS - 3) as f32;
22
23// Maximum bit length of a `powi` exponent for which the binary squaring chain is feasible. The
24// chain runs `n.bit_len() - 1` correctly-rounded squarings at a working precision that grows with
25// `n.bit_len()`, and compounds relative error ~`2^nlen · ulp`; for `nlen` in the millions/billions
26// (an `IBig` exponent far past `i64`) a single attempt exhausts memory. Exponents beyond `i64`
27// (`nlen > 64`) only ever produce a finite result when `|base| ≈ 1` (otherwise the magnitude
28// overflows the finite range), so they go to the `exp(y·ln x)` fallback instead of the chain.
29const MAX_POWI_CHAIN_BITS: usize = 64;
30
31// Guard charge for the `Bⁿ` powering chain inside `exp_compute` (the `sum.pow(Bⁿ)` binary
32// exponentiation). The chain compounds the per-op radius slack, and on non-power-of-two bases
33// every measured precision paid one systematic Ziv retry that base 2 never did (DBig
34// `exp`/`sinh`/`powf` and base-3 `exp` across the sweep; worst case ~10 decimal digits short
35// at 600 digits). A guard digit shrinks the series-entry radius
36// one-to-one while the chain's amplification stays put, so the miss converts directly into
37// guard digits: charging `n` (the reduction power whose bits are the chain length) leaves a
38// ~3× margin over the measured miss. Base 2 is not charged: its chain squares an exact power
39// with exact `Mag` base scaling (`Mag::from_base_pow::<2>` is `from_pow2`), and it measured
40// zero retries at every precision. An undersized charge only costs the retry it meant to
41// prevent — the loop's `max(guard, precision/2)` step still certifies on the second attempt.
42pub(crate) const fn pow_chain_guard<const B: Word>(n: usize) -> usize {
43    if B == 2 {
44        0
45    } else {
46        n
47    }
48}
49
50// Margin certifying a `powi` result is outside the finite range: the magnitude guard estimates the
51// result's log2 as `e · log2(base)` in f64, where `e` is up to `i64::MAX` and `isize::MAX as f64`
52// is itself rounded — together ~2^17 of f64 error near the boundary. A result whose log2 is within
53// this margin of the threshold is deferred to the squaring chain (whose `checked_mul` catches a
54// genuine overflow) rather than risk a false-positive overflow returning ±∞.
55const POWI_RANGE_MARGIN: f64 = (1 << 20) as f64;
56
57// `powi` (integer power), `powf`/`exp`/`exp_m1` route through Ziv-backed Context methods, which
58// require `R: ErrorBounds` for their correctness guarantee.
59impl<R: ErrorBounds, const B: Word> FBig<R, B> {
60    /// Raise the floating point number to an integer power.
61    ///
62    /// # Examples
63    ///
64    /// ```
65    /// # use dashu_base::ParseError;
66    /// # use dashu_float::DBig;
67    /// # use core::str::FromStr;
68    /// let a = DBig::from_str("-1.234")?;
69    /// assert_eq!(a.powi(10.into()), DBig::from_str("8.188")?);
70    /// # Ok::<(), ParseError>(())
71    /// ```
72    #[inline]
73    pub fn powi(&self, exp: IBig) -> FBig<R, B> {
74        self.context.unwrap_fp(self.context.powi(&self.repr, exp))
75    }
76
77    /// Raise the floating point number to an floating point power.
78    ///
79    /// # Examples
80    ///
81    /// ```
82    /// # use dashu_base::ParseError;
83    /// # use dashu_float::DBig;
84    /// # use core::str::FromStr;
85    /// let x = DBig::from_str("1.23")?;
86    /// let y = DBig::from_str("-4.56")?;
87    /// assert_eq!(x.powf(&y), DBig::from_str("0.389")?);
88    /// # Ok::<(), ParseError>(())
89    /// ```
90    #[inline]
91    pub fn powf(&self, exp: &Self) -> Self {
92        let context = Context::max(self.context, exp.context);
93        context.unwrap_fp(context.powf(&self.repr, &exp.repr, None))
94    }
95
96    /// Calculate the exponential function (`eˣ`) on the floating point number.
97    ///
98    /// # Examples
99    ///
100    /// ```
101    /// # use dashu_base::ParseError;
102    /// # use dashu_float::DBig;
103    /// # use core::str::FromStr;
104    /// let a = DBig::from_str("-1.234")?;
105    /// assert_eq!(a.exp(), DBig::from_str("0.2911")?);
106    /// # Ok::<(), ParseError>(())
107    /// ```
108    #[inline]
109    pub fn exp(&self) -> FBig<R, B> {
110        self.context.unwrap_fp(self.context.exp(&self.repr, None))
111    }
112
113    /// Calculate the exponential minus one function (`eˣ-1`) on the floating point number.
114    ///
115    /// # Examples
116    ///
117    /// ```
118    /// # use dashu_base::ParseError;
119    /// # use dashu_float::DBig;
120    /// # use core::str::FromStr;
121    /// let a = DBig::from_str("-0.1234")?;
122    /// assert_eq!(a.exp_m1(), DBig::from_str("-0.11609")?);
123    /// # Ok::<(), ParseError>(())
124    /// ```
125    #[inline]
126    pub fn exp_m1(&self) -> FBig<R, B> {
127        self.context
128            .unwrap_fp(self.context.exp_m1(&self.repr, None))
129    }
130}
131
132impl<R: Round> Context<R> {
133    /// Near-correct exp core: evaluate `exp(x)` (or `exp_m1(x)` when `minus_one`) at
134    /// `work_precision`, returning a [`Ball`] whose radius is derived mechanically.
135    ///
136    /// Shared by the Ziv-backed `exp`/`exp_m1` (which retry it) and usable directly where only a
137    /// near-correct value is needed. The caller must have pre-checked that the reduction quotient
138    /// `s = floor(x/ln B)` fits `isize` (astronomical `|x|` overflows and is handled before the
139    /// Ziv loop, since this closure can't return `Err`). `n` (the reduction power, `≈ √p`) is
140    /// derived from the *target* precision and is constant across retries.
141    pub(crate) fn exp_compute<const B: Word>(
142        &self,
143        x: &Repr<B>,
144        work_precision: usize,
145        minus_one: bool,
146        n: usize,
147        mut cache: Option<&mut ConstCache>,
148    ) -> Result<Ball<B>, FpError> {
149        // exp(x) = B^s · exp(r)^(Bⁿ), with r = x − s·ln(B) reduced so |r| < B⁻ⁿ.
150        let context = Context::<mode::HalfEven>::new(work_precision);
151        let x_ball = Ball::from_rounded(context.repr_round_ref(x), work_precision);
152
153        // When minus_one is true and |x| < 1/B, evaluate the Maclaurin series without scaling
154        // (no Bⁿ reduction, no powering — n_eff = 0).
155        let no_scaling = minus_one && x_ball.mid.log2_est() < -B.log2_est();
156        // `series_precision` mirrors the old FBig-op precision (max of the operands): the
157        // reduction's `extra` digits ride along into the series, keeping the same guard
158        // headroom the near-correct consumers (e.g. `with_base`) were tuned against.
159        let (s, r_ball, n_eff, series_precision) = if no_scaling {
160            (0isize, x_ball, 0usize, work_precision)
161        } else {
162            // The reduction quotient `s = floor(x / ln B)` amplifies ln(B)'s rounding error by
163            // |x|: a 1-ulp error in ln(B) shifts `s` (and thus the result exponent) by ~|x|/ln B.
164            // For large |x| the work precision is far too low to pin `s` — exp(5.7e14) at p=24 was
165            // certified with the exponent off by ~1000 — so compute ln(B) with `⌈log_B|x|⌉ + 2`
166            // extra digits, enough that the reduction contributes well under one work-ulp and the
167            // series/powering radius bounds the total error. (The bounds, not the point estimate,
168            // guard the inflation magnitude.)
169            let x_log2_ub = x_ball.mid.log2_bounds().1;
170            let extra = if x_log2_ub > 0.0 {
171                (x_log2_ub / B.log2_est()) as usize + 2
172            } else {
173                2
174            };
175            // ln(B) as a ball: the cached bases (2, 10, powers of 2) are correctly rounded (the
176            // fixed 8-ulp bound in `ln_base_ball` is sound there), while generic bases carry
177            // `ln_compute`'s mechanical radius (their atanh series error can be far larger than 8).
178            let logb_ball = Context::<mode::HalfEven>::new(work_precision + extra)
179                .ln_base_ball::<B>(reborrow_cache(&mut cache))?;
180            let x_sign = x_ball.mid.sign();
181            // floor(x / ln B) on the midpoints — `div_rem_euclid` lives on FBig, so wrap the
182            // bare mids (zero-cost) at their own working precisions (the old code's contexts).
183            // LIMITED contexts: an unlimited-precision division would never terminate.
184            let (s_big, _) = FBig::new(x_ball.mid.clone(), context).div_rem_euclid(FBig::new(
185                logb_ball.mid.clone(),
186                Context::new(work_precision + extra),
187            ));
188            let s: isize = match s_big.try_into() {
189                Ok(s) => s,
190                Err(_) => {
191                    // |x| is astronomical — the reduction quotient overflows isize. The magnitude
192                    // gate in `exp_internal` is meant to catch this first; reaching here is a
193                    // gray-zone miss, so surface the range error it would have returned.
194                    return Err(if x_sign == Sign::Positive {
195                        FpError::Overflow(Sign::Positive)
196                    } else {
197                        FpError::Underflow(Sign::Positive)
198                    });
199                }
200            };
201            // r = x − s·ln(B), as a ball: the cancellation and ln(B)'s error are tracked by the
202            // Ball propagation.
203            let scaled = logb_ball.scale_int(&IBig::from(s), work_precision + extra)?;
204            let r_ball = x_ball.sub(&scaled, work_precision + extra)?;
205            (s, r_ball, n, work_precision + extra)
206        };
207        let r_ball = r_ball.shift(-(n_eff as isize));
208
209        // Maclaurin series: exp(r) = 1 + Σ rⁱ/i! (exp_m1(x) = Σ xⁱ/i! when no_scaling).
210        let one = Ball::exact_int(IBig::ONE, series_precision);
211        let mut factorial = IBig::ONE;
212        let mut pow = r_ball.clone();
213        let mut sum = if no_scaling {
214            r_ball.clone()
215        } else {
216            one.add(&r_ball, series_precision)?
217        };
218        let mut k = 2u32;
219        loop {
220            factorial *= k;
221            pow = pow.mul(&r_ball, series_precision)?;
222
223            let increase =
224                pow.div(&Ball::exact(Repr::new(factorial.clone(), 0)), series_precision)?;
225            if increase.mid_le_ulp_lb(&sum, series_precision) {
226                break;
227            }
228            sum = sum.add(&increase, series_precision)?;
229            k += 1;
230        }
231
232        // Omitted series tail: the exp terms shrink by r/(i+1) < 1/4 (|r| < B⁻ⁿ), so the tail is
233        // < 2 ulps of sum.
234        sum.add_error(ulps::<B>(&sum.mid, series_precision, 2));
235
236        if no_scaling {
237            // exp_m1(x) = sum directly.
238            return Ok(sum);
239        }
240        // Powering: exp(r)^(Bⁿ) = sum^Bⁿ, via binary exponentiation (the compounding rounding is
241        // tracked by the Ball multiplications). The chain is exact only when the series sum is
242        // exact (impossible here — sum ≈ exp(r) with |r| < B⁻ⁿ), so the exact flag is ignored.
243        let bn = Repr::<B>::BASE.pow(n);
244        let v_ball = sum.pow(&bn, series_precision)?;
245
246        // B^s is an exact power-of-base shift: `exp(x) = B^s · exp(r)^(Bⁿ)`.
247        let v_shifted = v_ball.shift(s);
248
249        if minus_one {
250            // exp_m1(x) = exp(x) − 1; the subtraction folds one rounding ulp.
251            let one = Ball::exact_int(IBig::ONE, series_precision);
252            Ok(v_shifted.sub(&one, series_precision)?)
253        } else {
254            Ok(v_shifted)
255        }
256    }
257
258    /// `exp` of a *ball* input. [`exp_compute`](Self::exp_compute) evaluates on `x.mid`;
259    /// the input ball's own error `|θ| ≤ x.rad` then contributes `e^{x+rad_x}·rad_x` to the
260    /// result (the exponential's derivative is itself, evaluated at the ball's *upper
261    /// endpoint*): `|e^{x+θ} − e^x| ≤ e^x·(e^θ − 1) ≤ rad_x·e^{x+rad_x}`.
262    ///
263    /// The factor `e^{x+rad_x}` is bounded **without ever evaluating a negative-argument exp**:
264    /// `e^{x+rad_x} = e^{x.mid}·e^{rad_x} ≤ ‖result‖·exp_upper(rad_x)`, where `‖result‖` is the
265    /// ball's own magnitude [`Ball::mag`] — a proven upper bound on `e^{x.mid}` because the ball
266    /// covers it. Both factors are essential: dropping `‖result‖` (e.g. clamping the factor to
267    /// `Mag::ONE`, which is sound since `e^{x+rad_x} ≤ 1` for a nonpositive endpoint) throws away
268    /// the entire `e^x` magnitude and inflates the radius by `e^{−x}` — for a large negative
269    /// exponent (`powf` with a large `|y·ln x|` drives `x` to thousands) that is a relative
270    /// over-estimate of hundreds of digits, and Ziv can only certify by growing the working
271    /// precision past `|x|/log_B e`, turning a microsecond `powf` into seconds. `work_precision`
272    /// is the precision `x` was built at.
273    pub(crate) fn exp_ball<const B: Word>(
274        &self,
275        x: &Ball<B>,
276        work_precision: usize,
277        mut cache: Option<&mut ConstCache>,
278    ) -> Result<Ball<B>, FpError> {
279        let n = 1usize << (self.precision.bit_len() / 2);
280        let mut result =
281            self.exp_compute::<B>(&x.mid, work_precision, false, n, reborrow_cache(&mut cache))?;
282        if !x.rad.is_zero() {
283            let factor = result.mag().mul(&x.rad.exp_upper());
284            result.add_error(factor.mul(&x.rad));
285        }
286        Ok(result)
287    }
288
289    /// Directed saturation endpoint for an FBig result that has underflowed below the smallest
290    /// representable magnitude (its exponent would fall below `isize::MIN`). Outward modes round
291    /// the magnitude up to the smallest `B^{isize::MIN}` of the result's sign; toward-zero, the
292    /// opposite direction, and nearest round to signed zero. This mirrors the f32/f64 directed
293    /// underflow and is the shared endpoint that resolves [`FpError::Underflow`] in
294    /// [`Context::unwrap_fp`] — which `powi`/`powf` saturate through (their `exp` core reports the
295    /// underflow) — so a directed `pow` (e.g. `pow(10, y)` ≈ `exp(y·ln 10)`) saturates to the same
296    /// value `exp` does, keeping `Up ≥ Down` consistent across them. The endpoint carries the input
297    /// context, so a downstream op keeps a limited precision.
298    pub(crate) fn underflow_repr_endpoint<const B: Word>(&self, sign: Sign) -> Rounded<FBig<R, B>> {
299        let adj = if sign == Sign::Positive {
300            R::round_low_part(&IBig::ZERO, Sign::Positive, || Ordering::Less)
301        } else {
302            R::round_low_part(&IBig::ZERO, Sign::Negative, || Ordering::Less)
303        };
304        match adj {
305            AddOne => Inexact(FBig::new(Repr::new(IBig::ONE, isize::MIN), *self), AddOne),
306            SubOne => Inexact(
307                FBig::new(
308                    Repr::new(IBig::from_parts(Sign::Negative, UBig::ONE), isize::MIN),
309                    *self,
310                ),
311                SubOne,
312            ),
313            _ => Inexact(FBig::new(Repr::<B>::zero_with_sign(sign), *self), NoOp),
314        }
315    }
316
317    /// Directed saturation endpoint for an FBig result that has overflowed above the largest
318    /// representable magnitude (its exponent would exceed `isize::MAX`). Outward modes (Up/Away for
319    /// positive, Down/Away for negative) and nearest reach `±∞`; inward modes (toward-zero, and the
320    /// opposite-infinity direction) saturate to the largest finite `(Bᵖ−1) × B^{isize::MAX}` — the
321    /// all-`(B−1)` significand at the max exponent, mirroring MPFR's `mpfr_setmax` (which fills the
322    /// significand with all 1-bits *at the output precision* — the significand is `p` digits, not
323    /// the value's magnitude). The largest finite is ill-defined at unlimited precision, so this
324    /// panics when `precision == 0`.
325    pub(crate) fn overflow_repr_endpoint<const B: Word>(&self, sign: Sign) -> Rounded<FBig<R, B>> {
326        assert_limited_precision(self.precision);
327        let adj = if sign == Sign::Positive {
328            R::round_low_part(&IBig::ONE, Sign::Positive, || Ordering::Greater)
329        } else {
330            R::round_low_part(&IBig::NEG_ONE, Sign::Negative, || Ordering::Greater)
331        };
332        match adj {
333            AddOne => Inexact(FBig::new(Repr::infinity_with_sign(Sign::Positive), *self), AddOne),
334            SubOne => Inexact(FBig::new(Repr::infinity_with_sign(Sign::Negative), *self), SubOne),
335            _ => {
336                // Largest finite at this precision: (B^p − 1) × B^{isize::MAX}.
337                let max_mag = Repr::<B>::BASE.pow(self.precision) - UBig::ONE;
338                Inexact(
339                    FBig::new(Repr::new(IBig::from_parts(sign, max_mag), isize::MAX), *self),
340                    NoOp,
341                )
342            }
343        }
344    }
345}
346
347// `powi` (integer power), `powf` (non-integer exponent), `exp`, and `exp_m1` are correctly rounded
348// via the Ziv loop, so they require `R: ErrorBounds`. `powf` with an integer-valued exponent
349// delegates to `powi`.
350impl<R: ErrorBounds> Context<R> {
351    /// Raise the floating point number to an integer power under this context, correctly rounded
352    /// via a Ziv retry loop.
353    ///
354    /// `base^n` is computed by left-to-right binary exponentiation (repeated squaring); a negative
355    /// exponent computes `(1/base)^|n|`, so the sign-dependent overflow/underflow falls out
356    /// naturally. Each squaring compounds the relative error (it roughly doubles per step), so
357    /// after `n.bit_len()` squarings the error is bounded by about `2^nlen · ulp` — the Ziv radius
358    /// reflects that, and the loop retries with more guard digits until the working-precision
359    /// interval unambiguously determines the target rounding.
360    ///
361    /// # Examples
362    ///
363    /// ```
364    /// # use dashu_base::ParseError;
365    /// # use dashu_float::DBig;
366    /// # use core::str::FromStr;
367    /// use dashu_base::Approximation::*;
368    /// use dashu_float::{Context, round::{mode::HalfAway, Rounding::*}};
369    ///
370    /// let context = Context::<HalfAway>::new(2);
371    /// let a = DBig::from_str("-1.234")?;
372    /// assert_eq!(context.powi(&a.repr(), 10.into()), Ok(Inexact(DBig::from_str("8.2")?, AddOne)));
373    /// # Ok::<(), ParseError>(())
374    /// ```
375    ///
376    /// # Panics
377    ///
378    /// Panics if the precision is unlimited and the exponent is negative (the exact `1/base` is
379    /// not finite in general).
380    pub fn powi<const B: Word>(&self, base: &Repr<B>, exp: IBig) -> FpResult<FBig<R, B>> {
381        if base.is_infinite() {
382            return Err(FpError::InfiniteInput);
383        }
384        let (exp_sign, n) = exp.into_parts();
385        let negative = exp_sign == Sign::Negative;
386        if negative {
387            // a negative exponent needs 1/base, which is not finite at unlimited precision
388            assert_limited_precision(self.precision);
389        }
390
391        if n.is_zero() {
392            return Ok(Exact(FBig::ONE));
393        }
394        if n.is_one() {
395            if negative {
396                // base^(-1) = 1/base: a single correctly-rounded division
397                return self.div(&Repr::one(), base);
398            }
399            let repr = self.repr_round_ref(base);
400            return Ok(repr.map(|v| FBig::new(v, *self)));
401        }
402
403        // Zero base (±0): a positive exponent gives ±0, a negative one ±inf; the sign follows |n|'s
404        // parity. Short-circuit before the magnitude pre-check (whose log2 estimate is meaningless
405        // for zero) and before the squaring chain (which can't start from zero).
406        let odd = n.bit(0);
407        if base.significand.is_zero() {
408            let neg_sign = base.sign() == Sign::Negative && odd;
409            if negative {
410                let sign = if neg_sign {
411                    Sign::Negative
412                } else {
413                    Sign::Positive
414                };
415                return Ok(Exact(FBig::new(Repr::<B>::infinity_with_sign(sign), *self)));
416            }
417            let repr = if neg_sign {
418                Repr::<B>::neg_zero()
419            } else {
420                Repr::<B>::zero()
421            };
422            return Ok(Exact(FBig::new(repr, *self)));
423        }
424
425        // Magnitude pre-check: the result's log2 is `signed_exp · log2|base|`; outside the finite
426        // exponent range it short-circuits to overflow/underflow instead of letting the squaring
427        // chain overflow mid-computation (the Ziv closure below can't return `Err`).
428        //
429        // Use the *bounds* of log2(base), never the point estimate `log2_est`: when base is very
430        // close to 1 (a large significand with a large negative exponent), log2(base) is the
431        // difference of two large terms and suffers catastrophic cancellation — `log2_est` returns
432        // ~1e-4 of f32 noise rather than ~0. Scaled by a large exponent that noise crosses the
433        // overflow threshold, which on 32-bit is only isize::MAX·log2(B) ≈ 7e9 (vs ≈3e19 on 64-bit),
434        // so the guard fires spuriously and returns ±inf — see issue #95 (it crashed high-precision
435        // `FBig::with_base` on wasm32/i686). The bounds are derived from the exact significand bit
436        // length, so they don't cancel. Declare an extreme result only when a bound certifies it
437        // (no false positives); anything ambiguous is computed.
438        let (base_log2_lb, base_log2_ub) = base.log2_bounds();
439        let base_log2_lb = base_log2_lb as f64;
440        let base_log2_ub = base_log2_ub as f64;
441        let threshold = (isize::MAX as f64) * (B.log2_est() as f64);
442        let threshold_certain = threshold + POWI_RANGE_MARGIN;
443        let exp_f64 = i64::try_from(&n).ok().map(|e| e as f64);
444        // `lb_side` certifies |base| > 1 by a wide margin; `ub_side` certifies |base| < 1. (For the
445        // None case |exp| is unbounded, so the bound's sign alone decides.) A negative exponent
446        // swaps which side over- vs underflows.
447        let lb_side = match exp_f64 {
448            Some(e) => e * base_log2_lb > threshold_certain,
449            None => base_log2_lb > 0.0,
450        };
451        let ub_side = match exp_f64 {
452            Some(e) => e * base_log2_ub < -threshold_certain,
453            None => base_log2_ub < 0.0,
454        };
455        if lb_side || ub_side {
456            // |base|>1 (lb_side): positive exp → overflow, negative exp → underflow.
457            // |base|<1 (ub_side): positive exp → underflow, negative exp → overflow.
458            let overflow = (lb_side && !negative) || (ub_side && negative);
459            let sign = if base.sign() == Sign::Negative && odd {
460                Sign::Negative
461            } else {
462                Sign::Positive
463            };
464            return Err(if overflow {
465                FpError::Overflow(sign)
466            } else {
467                FpError::Underflow(sign)
468            });
469        }
470
471        // |exp| doesn't fit i64 and the bounds straddle 0, so |base| is within the bounds of 1.
472        // If it is *exactly* ±1 the result is ±1 for any exponent (short-circuit so the squaring
473        // chain doesn't iterate over exp's enormous bit length); otherwise |base| ≈ 1 but ≠ 1, the
474        // huge power is still finite, and we fall through to compute it.
475        if exp_f64.is_none() && base.significand.is_one() && base.exponent == 0 {
476            let repr = if base.sign() == Sign::Negative && odd {
477                Repr::<B>::neg_one()
478            } else {
479                Repr::<B>::one()
480            };
481            return Ok(Exact(FBig::new(repr, *self)));
482        }
483
484        let nlen = n.bit_len();
485        // Exponents past `i64` make the squaring chain infeasible (`nlen - 1` squarings at a
486        // working precision that grows with `nlen`) and, when the magnitude also overflows the
487        // finite range, can drive it to exhaust memory. The only finite results at that scale have
488        // `|base| ≈ 1`, which the `exp(y·ln x)` fallback computes without scaling the working
489        // precision with `nlen` — so it cannot allocate unboundedly.
490        if nlen > MAX_POWI_CHAIN_BITS {
491            let signed_exp = IBig::from_parts(exp_sign, n.clone());
492            return self.powi_via_exp_log(base, &signed_exp);
493        }
494        // The chain runs on the magnitude `start` (base, or its reciprocal for a negative
495        // exponent), whose range-error sign is the *intermediate* sign; remap any overflow/underflow
496        // to the true result sign (base sign × exponent parity) so the directed endpoint is correct.
497        let result_sign = if base.sign() == Sign::Negative && odd {
498            Sign::Negative
499        } else {
500            Sign::Positive
501        };
502        let initial_guard = nlen + self.base_guard_digits::<B>() + 2;
503        self.ziv(initial_guard, |guard| {
504            let pw = self.precision + guard;
505            let work = Context::<mode::HalfEven>::new(pw);
506            // start from base (positive exponent, always exact) or its working-precision reciprocal
507            // (negative exponent, exact only when 1/base is exactly representable). A range error
508            // here (e.g. 1/base underflows for an extreme base) is remapped to the result sign and
509            // propagated — saturating would feed the chain an infinity or zero it can't recover from.
510            let start_ball = if negative {
511                match work.div(&Repr::<B>::one(), base) {
512                    Ok(v) => Ball::from_rounded(v.map(FBig::into_repr), pw),
513                    Err(FpError::Overflow(_)) => return Err(FpError::Overflow(result_sign)),
514                    Err(FpError::Underflow(_)) => return Err(FpError::Underflow(result_sign)),
515                    Err(e) => return Err(e),
516                }
517            } else {
518                Ball::exact(base.clone())
519            };
520            // The squaring chain compounds the error mechanically; when the whole chain is exact
521            // (exact start, no rounding anywhere) the radius stays 0 — the
522            // exactly-representable directed-rounding case that no nonzero radius could certify.
523            let res_ball = start_ball.pow(&n, pw).map_err(|e| match e {
524                FpError::Overflow(_) => FpError::Overflow(result_sign),
525                FpError::Underflow(_) => FpError::Underflow(result_sign),
526                other => other,
527            })?;
528            Ok(res_ball.to_value_radius::<R>(&Context::<R>::new(pw)))
529        })
530    }
531
532    /// Raise the floating point number to an floating point power under this context.
533    ///
534    /// A non-integer exponent is correctly rounded via a Ziv loop. An integer-valued exponent
535    /// delegates to [`powi`](Context::powi) (binary exponentiation), which also accepts a negative
536    /// base — its sign is fixed by the exponent's parity — so `pow(-x, n)` is in domain here for
537    /// integer `n`. Both paths are correctly rounded.
538    ///
539    /// # Examples
540    ///
541    /// ```
542    /// # use dashu_base::ParseError;
543    /// # use dashu_float::DBig;
544    /// # use core::str::FromStr;
545    /// use dashu_base::Approximation::*;
546    /// use dashu_float::{Context, round::{mode::HalfAway, Rounding::*}};
547    ///
548    /// let context = Context::<HalfAway>::new(2);
549    /// let x = DBig::from_str("1.23")?;
550    /// let y = DBig::from_str("-4.56")?;
551    /// assert_eq!(context.powf(&x.repr(), &y.repr(), None), Ok(Inexact(DBig::from_str("0.39")?, AddOne)));
552    /// # Ok::<(), ParseError>(())
553    /// ```
554    ///
555    /// # Panics
556    ///
557    /// Panics if the precision is unlimited.
558    pub fn powf<const B: Word>(
559        &self,
560        base: &Repr<B>,
561        exp: &Repr<B>,
562        cache: Option<&mut ConstCache>,
563    ) -> FpResult<FBig<R, B>> {
564        if base.is_infinite() || exp.is_infinite() {
565            return Err(FpError::InfiniteInput);
566        }
567        assert_limited_precision(self.precision);
568
569        // shortcuts
570        if exp.is_pos_zero() || exp.is_neg_zero() {
571            // pow(x, ±0) = 1 for any base (IEEE 754 §9.2.1); `-0` is numerically zero, so it
572            // must take the same shortcut as `+0` (otherwise a negative base falls through to
573            // the OutOfDomain path below).
574            return Ok(Exact(FBig::ONE));
575        } else if exp.is_one() {
576            let repr = self.repr_round_ref(base);
577            return Ok(repr.map(|v| FBig::new(v, *self)));
578        } else if base.significand.is_zero() {
579            // With a *float* exponent the result on a zero base is the positive one — this
580            // matches the common float-pow convention (e.g. CPython: `(-0.0) ** y == 0.0`),
581            // which doesn't track the parity of the exponent:
582            //   pow(±0, y > 0) = +0,    pow(±0, y < 0) = +inf.
583            // For the sign-correct result (e.g. `pow(-0, odd) = -0`), use the integer-exponent
584            // [`powi`](Context::powi). Short-circuiting here also avoids the negative-base path.
585            return Ok(Exact(if exp.sign() == Sign::Negative {
586                FBig::new(Repr::infinity(), *self)
587            } else {
588                FBig::ZERO
589            }));
590        }
591        if base.is_one() {
592            // pow(1, y) = 1 for any finite y (exp is finite here — infinities were rejected above).
593            return Ok(Exact(FBig::ONE));
594        }
595
596        // Integer-valued exponent: delegate to the integer-power kernel (binary exponentiation),
597        // itself correctly rounded via its own Ziv loop. This sidesteps the `exp(y·ln x)`
598        // amplification entirely, and lets a negative base through — `powi` fixes the sign from
599        // the exponent's parity. Gated on `is_int` (a cheap exponent check) so the non-integer
600        // common case skips `to_int`.
601        if exp.is_int() {
602            return self.powi(base, exp.to_int().value());
603        }
604
605        if base.sign() == Sign::Negative {
606            // A non-integer exponent on a negative base has no real value.
607            return Err(FpError::OutOfDomain);
608        }
609
610        // `base` is positive here (negative non-integer base returned OutOfDomain above).
611        self.pow_exp_log(base, exp, cache)
612    }
613
614    /// `x^y = exp(y·ln x)` for `pos_base > 0`, correctly rounded via a Ziv loop — the shared core
615    /// of [`powf`](Self::powf) (non-integer exponents) and the [`powi`](Self::powi) fallback for
616    /// exponents past the squaring chain's feasible range.
617    ///
618    /// The radius is **derived mechanically**: `ln_compute`, the multiplication by the rounded
619    /// exponent and [`exp_ball`](Self::exp_ball) are each [`Ball`] operations, so their errors
620    /// compose through the ordinary rules. `exp` amplifies the absolute error of `y·ln x` by the
621    /// result magnitude — that amplification is `exp_ball`'s input-error fold, which scales by
622    /// `result.mag()` (see its doc: both factors there are load-bearing). Every radius involved
623    /// is taken at the *working* precision, so it shrinks as `B^{-guard}` and the containment
624    /// test converges. (A radius computed at unlimited precision would be constant across
625    /// retries and never converge for a value near a rounding boundary.)
626    ///
627    /// Overflow/underflow of `exp(y·ln x)` is detected inside the Ziv closure by `exp` itself
628    /// (which returns `Err(Overflow)` / `Err(Underflow)`) and propagated — the result is positive
629    /// (argument to `exp`), so overflow is `+∞` and underflow carries `+` sign; callers that need a
630    /// negative result (the `powi` fallback for a negative base) flip the sign of both the value
631    /// and the error.
632    fn pow_exp_log<const B: Word>(
633        &self,
634        pos_base: &Repr<B>,
635        exp: &Repr<B>,
636        mut cache: Option<&mut ConstCache>,
637    ) -> FpResult<FBig<R, B>> {
638        // The `exp_ball` powering chain amplifies the input radius by `Bⁿ` — the same compounding
639        // [`pow_chain_guard`] charges for `exp` — but here it acts on `y·ln x`'s radius against a
640        // thin `+10` guard, and *every* base measured the retry (base-2 `powf` included), so
641        // the charge is unconditional. It is also the one site the
642        // base-10 sweep showed `n` undersized (DBig `powf 10^0.5` @150 still retried), so the
643        // chain length is charged twice.
644        let initial_guard =
645            self.base_guard_digits::<B>() + 10 + 2 * (1usize << (self.precision.bit_len() / 2));
646        self.ziv(initial_guard, |guard| {
647            let wp = self.precision + guard;
648            // exp(y·ln x) as a Ball chain: the ln and the exponent rounding compose mechanically,
649            // and the exp input error is folded in via `exp_ball`. The radius shrinks with guard
650            // now that `ln_compute`'s s<0 reduction no longer inflates its error count.
651            let ln_ball = self.ln_compute::<B>(pos_base, wp, false, reborrow_cache(&mut cache))?;
652            let work = Context::<mode::HalfEven>::new(wp);
653            let exp_input = Ball::from_rounded(work.repr_round_ref(exp), wp);
654            let arg_ball = ln_ball.mul(&exp_input, wp)?;
655            let result_ball = self.exp_ball::<B>(&arg_ball, wp, reborrow_cache(&mut cache))?;
656            Ok(result_ball.to_value_radius::<R>(&Context::<R>::new(wp)))
657        })
658    }
659
660    /// `powi` fallback for exponents past the squaring chain's feasible bit length: compute
661    /// `base^signed_exp = exp(signed_exp · ln|base|)`. The integer exponent is an exact float
662    /// (significand `|signed_exp|`, exponent `0`), so this delegates to [`pow_exp_log`](Self::pow_exp_log)
663    /// — reusing its Ziv rounding — and then fixes the result sign from the
664    /// exponent's parity for a negative base. The working precision never scales with
665    /// `signed_exp.bit_length()`, so (unlike the squaring chain) this cannot allocate unboundedly.
666    fn powi_via_exp_log<const B: Word>(
667        &self,
668        base: &Repr<B>,
669        signed_exp: &IBig,
670    ) -> FpResult<FBig<R, B>> {
671        let neg_base = base.sign() == Sign::Negative;
672        // `(-base)^n = (-1)^n · base^n`, so the magnitude is always `|base|^n` and only the sign
673        // depends on parity. `pow_exp_log` returns the positive magnitude; flip it (and the
674        // overflow/underflow sign) when the base is negative and the exponent is odd.
675        let odd = signed_exp.clone().into_parts().1.bit(0);
676        let result_sign = if neg_base && odd {
677            Sign::Negative
678        } else {
679            Sign::Positive
680        };
681        let base_mag = if neg_base {
682            let (_, mag) = base.significand().clone().into_parts();
683            Repr::<B>::new(IBig::from_parts(Sign::Positive, mag), base.exponent())
684        } else {
685            base.clone()
686        };
687        let exp_repr = Repr::new(signed_exp.clone(), 0);
688        match self.pow_exp_log(&base_mag, &exp_repr, None) {
689            Ok(rounded) => Ok(rounded.map(|v| if result_sign == Sign::Negative { -v } else { v })),
690            Err(FpError::Overflow(_)) => Err(FpError::Overflow(result_sign)),
691            Err(FpError::Underflow(_)) => Err(FpError::Underflow(result_sign)),
692            Err(e) => Err(e),
693        }
694    }
695
696    /// Calculate the exponential function (`eˣ`) on the floating point number under this context.
697    ///
698    /// # Examples
699    ///
700    /// ```
701    /// # use dashu_base::ParseError;
702    /// # use dashu_float::DBig;
703    /// # use core::str::FromStr;
704    /// use dashu_base::Approximation::*;
705    /// use dashu_float::{Context, round::{mode::HalfAway, Rounding::*}};
706    ///
707    /// let context = Context::<HalfAway>::new(2);
708    /// let a = DBig::from_str("-1.234")?;
709    /// assert_eq!(context.exp(&a.repr(), None), Ok(Inexact(DBig::from_str("0.29")?, NoOp)));
710    /// # Ok::<(), ParseError>(())
711    /// ```
712    #[inline]
713    pub fn exp<const B: Word>(
714        &self,
715        x: &Repr<B>,
716        cache: Option<&mut ConstCache>,
717    ) -> FpResult<FBig<R, B>> {
718        if x.is_infinite() {
719            return Ok(Exact(FBig::new(
720                match x.sign() {
721                    Sign::Positive => Repr::infinity(),
722                    Sign::Negative => Repr::zero(),
723                },
724                *self,
725            )));
726        }
727        self.exp_internal(x, false, cache)
728    }
729
730    /// Calculate the exponential minus one function (`eˣ-1`) on the floating point number under this context.
731    ///
732    /// # Examples
733    ///
734    /// ```
735    /// # use dashu_base::ParseError;
736    /// # use dashu_float::DBig;
737    /// # use core::str::FromStr;
738    /// use dashu_base::Approximation::*;
739    /// use dashu_float::{Context, round::{mode::HalfAway, Rounding::*}};
740    ///
741    /// let context = Context::<HalfAway>::new(2);
742    /// let a = DBig::from_str("-0.1234")?;
743    /// assert_eq!(context.exp_m1(&a.repr(), None), Ok(Inexact(DBig::from_str("-0.12")?, SubOne)));
744    /// # Ok::<(), ParseError>(())
745    /// ```
746    #[inline]
747    pub fn exp_m1<const B: Word>(
748        &self,
749        x: &Repr<B>,
750        cache: Option<&mut ConstCache>,
751    ) -> FpResult<FBig<R, B>> {
752        if x.is_infinite() {
753            return match x.sign() {
754                Sign::Positive => Ok(Exact(FBig::new(Repr::infinity(), *self))),
755                Sign::Negative => Ok(Exact(-FBig::ONE)), // exp_m1(−∞) = −1
756            };
757        }
758        self.exp_internal(x, true, cache)
759    }
760
761    // The reduction stays in the *base-`B`* logarithm: `exp(x) = B^s · exp(r/Bⁿ)^(Bⁿ)` with
762    // `r = x − s·ln B`. A base-2 form (`r = x − s·ln 2`, powering `2ⁿ`) is deliberately **not**
763    // used: for a non-power-of-two base the `2^s` scaling is a multi-digit value (≈ s·log₂B⁻¹·log₁₀2
764    // digits) that would have to be materialized to multiply in, where the base-`B` form is an
765    // exact O(1) exponent shift; and for a power-of-two base the two forms coincide (`B = 2` ⇒
766    // `ln B = ln 2`, `B^s = 2^s`, `Bⁿ = 2ⁿ`), so this formulation is already the optimal one.
767    // `pow_exact(Bⁿ)` is binary exponentiation (~n·log₂B squarings), tracked exactly by the Ball.
768
769    fn exp_internal<const B: Word>(
770        &self,
771        x: &Repr<B>,
772        minus_one: bool,
773        mut cache: Option<&mut ConstCache>,
774    ) -> FpResult<FBig<R, B>> {
775        assert_finite(x);
776        let input_sign = x.sign();
777
778        if x.significand.is_zero() {
779            // exp(±0) = 1; exp_m1(±0) = ±0 (IEEE 754 §9.2.1 preserves the sign of zero).
780            // These exact results need no rounding, so handle them before the
781            // limited-precision assertion: a precision-0 (unlimited) FBig such as the
782            // one produced by `try_from(0.0)` must still compute exp/exp_m1 exactly.
783            return match minus_one {
784                false => Ok(Exact(FBig::ONE)),
785                true => {
786                    let zero = if input_sign == Sign::Negative {
787                        FBig::new(Repr::neg_zero(), Context::new(0))
788                    } else {
789                        FBig::ZERO
790                    };
791                    Ok(Exact(zero))
792                }
793            };
794        }
795
796        assert_limited_precision(self.precision);
797
798        // For sufficiently negative x, exp(x) is below half an ulp of -1, so exp_m1(x) is -1 plus a
799        // sub-ulp residual and its rounding is fully determined (Up/Zero -> the next representable
800        // above -1; the other modes -> -1). The Ziv loop cannot certify that result: the
801        // working-precision value collapses to exactly -1, and a directed rounding preimage is
802        // one-sided, so the containment test never resolves and the loop runs to its retry cap.
803        // Short-circuit to the same mode-aware endpoint used for the underflowed case. The cutoff is
804        // exp(x) < half-ulp(-1): -1 sits on a power-of-B boundary, so the spacing just below it is
805        // B^-p and the cutoff is |x| > p·ln(B) + ln 2. Compare the lower bound of log2|x| against an
806        // upper bound of log2(threshold) so a borderline input still falls through to Ziv (which
807        // converges there) rather than being mis-rounded.
808        if minus_one && input_sign == Sign::Negative {
809            let thresh = self.precision as f32 * B.log2_est() * core::f32::consts::LN_2
810                + core::f32::consts::LN_2;
811            if x.log2_bounds().0 > thresh.log2_bounds().1 {
812                return Ok(self.near_one_endpoint::<B>(Sign::Negative));
813            }
814        }
815
816        // No-OOM magnitude gate: for an `x` whose exponent is near `isize::MAX`, the reduction
817        // quotient `s = floor(x/ln B)` in `exp_compute` would allocate a GB-scale `IBig`, so reject
818        // astronomical |x| here (via the cheap `log2_est` fast-skip) before the Ziv loop runs the
819        // division. The probe inflates `ln B` with the same `⌈log_B|x|⌉ + 2` extra digits
820        // `exp_compute` uses, so its `s` verdict matches the computation's. (`exp_compute` also
821        // re-checks `s.try_into()` as a gray-zone backstop, propagating an error if the gate and
822        // computation ever disagree — so a miss degrades to the directed endpoint, not a panic.)
823        // `abs` via the [`Abs`] trait (the `f32` inherent method is std-only before 1.85, and
824        // the MSRV workspace check compiles this crate without `std`); the explicit trait path
825        // needs no `use`, whose import would read as unused in std builds (the inherent wins)
826        if dashu_base::Abs::abs(x.log2_est()) > EXP_OVERFLOW_PROBE_LOG2 {
827            let x_log2_ub = x.log2_bounds().1;
828            let extra = if x_log2_ub > 0.0 {
829                (x_log2_ub / B.log2_est()) as usize + 2
830            } else {
831                2
832            };
833            let probe = Context::<R>::new(self.precision + 64 + extra);
834            let logb = probe.ln_base::<B>(reborrow_cache(&mut cache));
835            let x_probe = FBig::new(probe.repr_round_ref(x).value(), probe);
836            let s_probe = x_probe.div_rem_euclid(logb).0;
837            if <isize as core::convert::TryFrom<IBig>>::try_from(s_probe).is_err() {
838                // exp(huge +) overflows to +∞ (the directed endpoint handles every mode); exp(huge −)
839                // is a positive value below the smallest representable, so it underflows (the directed
840                // endpoint gives +0 / smallest-positive); exp_m1(huge −) ≈ −1 stays a finite value
841                // just above −1 (the short-circuit above usually catches this first).
842                return if input_sign == Sign::Positive {
843                    Err(FpError::Overflow(Sign::Positive))
844                } else if minus_one {
845                    Ok(self.near_one_endpoint::<B>(Sign::Negative))
846                } else {
847                    Err(FpError::Underflow(Sign::Positive))
848                };
849            }
850        }
851
852        // Correct rounding via the Ziv loop. Guards: log_B(p) for the series summation/squaring
853        // rounding, plus `n` for the Bⁿ powering amplification — halved from the pre-Ziv `2n`,
854        // since Ziv (not the guard count) now certifies correctness — plus the powering chain's
855        // radius charge ([`pow_chain_guard`]). `n ≈ √p` is derived from the target precision and
856        // is constant across retries.
857        let series_guard = self.base_guard_digits::<B>();
858        let n = 1usize << (self.precision.bit_len() / 2);
859        self.ziv(series_guard + n + pow_chain_guard::<B>(n), |guard| {
860            Ok(self
861                .exp_compute::<B>(
862                    x,
863                    self.precision + guard,
864                    minus_one,
865                    n,
866                    reborrow_cache(&mut cache),
867                )?
868                .to_value_radius::<R>(&Context::<R>::new(self.precision + guard)))
869        })
870    }
871}
872
873#[cfg(test)]
874mod tests {
875    use super::*;
876    use crate::round::mode;
877
878    #[test]
879    fn test_exp_overflow_is_infinity() {
880        let ctx = Context::<mode::HalfEven>::new(53);
881        // exp(huge) overflows the isize exponent range -> Overflow at Context level.
882        // Need x large enough that floor(x/ln2) > isize::MAX, i.e. x > ~2^62.5.
883        let huge = Repr::new(IBig::from(1) << 63, 0);
884        assert_eq!(ctx.exp::<2>(&huge, None), Err(FpError::Overflow(Sign::Positive)));
885
886        // exp(huge −) is a positive value below the smallest representable -> Underflow at the
887        // Context layer; the directed endpoint is +0 under HalfEven (nearest), smallest-positive
888        // under Up.
889        let neg = Repr::new(-(IBig::from(1) << 63), 0);
890        assert_eq!(ctx.exp::<2>(&neg, None), Err(FpError::Underflow(Sign::Positive)));
891        assert!(ctx.unwrap_fp(ctx.exp::<2>(&neg, None)).repr().is_pos_zero(), "HalfEven -> +0");
892        let up = Context::<mode::Up>::new(53);
893        let up_val = up.unwrap_fp(up.exp::<2>(&neg, None));
894        assert_eq!(up_val.repr().significand(), &IBig::from(1), "Up -> smallest positive");
895        assert_eq!(up_val.repr().exponent(), isize::MIN);
896
897        // exp_m1(huge negative) -> -1 (a finite value, not an error)
898        let m1 = ctx.exp_m1::<2>(&neg, None).unwrap().value();
899        assert_eq!(m1, -FBig::<mode::HalfEven>::ONE);
900    }
901
902    // Directed rounding at the extreme-negative underflow: exp(x) for huge negative x is
903    // a positive value below the smallest representable FBig; exp_m1(x) = exp(x) − 1 is just above
904    // −1. The blanket +0 / Exact(−1) saturation was mode-blind — it returned +0 under Up and
905    // Exact(−1) under Up for exp_m1, violating Up ≥ Down.
906    #[test]
907    fn test_exp_extreme_negative_directed() {
908        // x = -2^63, precision 1 (exactly representable).
909        let up = FBig::<mode::Up>::from_parts(-IBig::ONE, 63);
910        let down = FBig::<mode::Down>::from_parts(-IBig::ONE, 63);
911        assert_eq!(up.precision(), 1);
912
913        // exp(-2^63): Up → smallest positive (1 × 2^{isize::MIN}); Down → +0.
914        let up_exp = up.exp();
915        let down_exp = down.exp();
916        assert_eq!(up_exp.repr().significand(), &IBig::from(1));
917        assert_eq!(up_exp.repr().exponent(), isize::MIN);
918        assert!(down_exp.repr().is_pos_zero(), "Down exp(huge −) is +0");
919        assert!(up_exp > down_exp, "Up(exp) > Down(exp)");
920
921        // exp_m1(-2^63) ∈ (-1, -1/2): at precision 1, Up → -1/2 (next above -1); Down → -1.
922        let up_m1 = up
923            .context()
924            .exp_m1(up.repr(), None)
925            .expect("finite exp_m1 input");
926        let down_m1 = down
927            .context()
928            .exp_m1(down.repr(), None)
929            .expect("finite exp_m1 input");
930        let expected_up = FBig::<mode::Up>::from_parts(-IBig::ONE, -1); // -1/2
931        assert!(!matches!(up_m1, Exact(_)), "exp_m1(huge −) is inexact under Up");
932        assert!(!matches!(down_m1, Exact(_)), "exp_m1(huge −) is inexact under Down too");
933        assert_eq!(up_m1.value().repr(), expected_up.repr());
934        assert_eq!(down_m1.value(), -FBig::<mode::Down>::ONE);
935    }
936
937    // exp_m1 of a large negative x where the reduction quotient still fits isize (so the overflow
938    // short-circuit doesn't fire) but exp(x) is below the result precision. The true value is
939    // -1 + (sub-ulp residual), so directed/nearest rounding is fully determined; the directed
940    // preimage being one-sided means Ziv cannot certify it, so it is short-circuited to the
941    // mode-aware endpoint. Verifies the result matches the directed saturation at several
942    // magnitudes/precisions (and that it does not regress to a many-retry Ziv loop).
943    #[test]
944    fn test_exp_m1_large_negative_directed_saturation() {
945        for &(e, p) in &[(50i32, 2usize), (50, 53), (100, 53), (1000, 53), (100, 128)] {
946            let up = FBig::<mode::Up, 2>::from_parts(IBig::from(-1), e as isize)
947                .with_precision(p)
948                .value()
949                .exp_m1();
950            let down = FBig::<mode::Down, 2>::from_parts(IBig::from(-1), e as isize)
951                .with_precision(p)
952                .value()
953                .exp_m1();
954            // Up -> next representable above -1 = -(2^p - 1) * 2^-p; Down -> -1.
955            let next_up_mag = (IBig::from(1) << p) - IBig::from(1);
956            let expected_up = FBig::<mode::Up, 2>::from_parts(-next_up_mag, -(p as isize));
957            assert_eq!(up.repr(), expected_up.repr(), "Up exp_m1(-2^{e}) p={p}");
958            assert_eq!(
959                down.repr(),
960                FBig::<mode::Down, 2>::NEG_ONE.repr(),
961                "Down exp_m1(-2^{e}) p={p}"
962            );
963            // The endpoint must carry the input precision: a precision-0 result would make a
964            // downstream op panic via `assert_limited_precision(0)`.
965            assert_eq!(up.precision(), p, "Up exp_m1(-2^{e}) p={p} lost precision");
966            assert_eq!(down.precision(), p, "Down exp_m1(-2^{e}) p={p} lost precision");
967            assert!(up > down, "Up > Down for exp_m1(-2^{e}) p={p}");
968        }
969    }
970
971    // exp(huge −) saturates to +0 (or the smallest positive under Up/Away). The endpoint must
972    // carry the input precision too — the precision-0 `FBig::ZERO` previously returned here
973    // tripped `assert_limited_precision(0)` on a downstream op.
974    #[test]
975    fn test_exp_extreme_negative_endpoint_precision() {
976        for &(e, p) in &[(50i32, 53usize), (100, 53), (1000, 53), (100, 128)] {
977            let up = FBig::<mode::Up, 2>::from_parts(-IBig::ONE, e as isize)
978                .with_precision(p)
979                .value()
980                .exp();
981            let down = FBig::<mode::Down, 2>::from_parts(-IBig::ONE, e as isize)
982                .with_precision(p)
983                .value()
984                .exp();
985            assert_eq!(up.precision(), p, "Up exp(-2^{e}) p={p} lost precision");
986            assert_eq!(down.precision(), p, "Down exp(-2^{e}) p={p} lost precision");
987            // A downstream op must not panic on the saturated endpoint.
988            let _ = down.sqrt();
989            assert!(up > down, "Up > Down for exp(-2^{e}) p={p}");
990        }
991    }
992
993    // Directed underflow through `powi`/`powf` must match `exp` (pow(x,y) = exp(y·ln x)) so the
994    // `Up ≥ Down` invariant holds across them. Previously `pow` saturated to signed zero under
995    // every mode, so `Up(pow(10, huge−))` was `+0` while `Up(exp(huge−·ln 10))` was the smallest
996    // positive — the two disagreed on the same mathematical value.
997    #[test]
998    fn test_pow_directed_underflow() {
999        let p = 53;
1000        // |exp| · log2(10) > isize::MAX ⇒ the result exponent falls below isize::MIN (underflow).
1001        let huge_neg = IBig::from(-9_000_000_000_000_000_000_i64);
1002
1003        // powi(10, huge−): positive tiny result. Up → smallest positive, Down/Zero → +0.
1004        let up = FBig::<mode::Up, 2>::from_parts(IBig::from(10), 0)
1005            .with_precision(p)
1006            .value()
1007            .powi(huge_neg.clone());
1008        let down = FBig::<mode::Down, 2>::from_parts(IBig::from(10), 0)
1009            .with_precision(p)
1010            .value()
1011            .powi(huge_neg.clone());
1012        let zero = FBig::<mode::Zero, 2>::from_parts(IBig::from(10), 0)
1013            .with_precision(p)
1014            .value()
1015            .powi(huge_neg.clone());
1016        assert_eq!(up.repr().significand(), &IBig::from(1));
1017        assert_eq!(up.repr().exponent(), isize::MIN);
1018        assert!(down.repr().is_pos_zero());
1019        assert!(zero.repr().is_pos_zero());
1020        assert!(up > down);
1021
1022        // powi(-10, huge odd −): negative tiny result. Up → -0, Down → smallest negative.
1023        let odd = IBig::from(-9_000_000_000_000_000_001_i64);
1024        let nup = FBig::<mode::Up, 2>::from_parts(IBig::from(-10), 0)
1025            .with_precision(p)
1026            .value()
1027            .powi(odd.clone());
1028        let ndown = FBig::<mode::Down, 2>::from_parts(IBig::from(-10), 0)
1029            .with_precision(p)
1030            .value()
1031            .powi(odd.clone());
1032        assert!(nup.repr().is_neg_zero());
1033        assert!(ndown.repr().sign() == Sign::Negative && ndown.repr().exponent() == isize::MIN);
1034        assert!(nup > ndown);
1035
1036        // powf(2, y) with |y| > isize::MAX underflows and agrees with exp(y·ln 2).
1037        let ymag = IBig::from(-10_000_000_000_000_000_000_i128);
1038        let y_up = FBig::<mode::Up, 2>::from_parts(ymag.clone(), 0)
1039            .with_precision(p)
1040            .value();
1041        let y_down = FBig::<mode::Down, 2>::from_parts(ymag.clone(), 0)
1042            .with_precision(p)
1043            .value();
1044        let pf_up = FBig::<mode::Up, 2>::from_parts(IBig::from(2), 0)
1045            .with_precision(p)
1046            .value()
1047            .powf(&y_up);
1048        let pf_down = FBig::<mode::Down, 2>::from_parts(IBig::from(2), 0)
1049            .with_precision(p)
1050            .value()
1051            .powf(&y_down);
1052        assert_eq!(pf_up.repr().significand(), &IBig::from(1));
1053        assert_eq!(pf_up.repr().exponent(), isize::MIN);
1054        assert!(pf_down.repr().is_pos_zero());
1055        // Same value as exp(y·ln 2) under the same mode.
1056        let ln2 = FBig::<mode::Up, 2>::from_parts(IBig::from(2), 0)
1057            .with_precision(p)
1058            .value()
1059            .ln();
1060        let exp_up = (&y_up * &ln2)
1061            .with_precision(p)
1062            .value()
1063            .with_rounding::<mode::Up>()
1064            .exp();
1065        assert_eq!(exp_up.repr(), pf_up.repr(), "powf and exp disagree on directed underflow");
1066    }
1067
1068    // Directed overflow through `exp`/`powi`: outward modes reach ±∞, inward modes (toward-zero,
1069    // opposite-infinity) saturate to the largest finite `(Bᵖ−1) × B^{isize::MAX}` — the all-ones
1070    // significand at the output precision, mirroring MPFR's `mpfr_setmax`. (Hyperbolic `sinh`/`cosh`
1071    // overflow under nearest is unchanged — still ±∞.)
1072    #[test]
1073    fn test_directed_overflow() {
1074        let p = 53usize;
1075        let max_sig = (IBig::ONE << p) - IBig::ONE;
1076
1077        // exp(2^63): overflows. Up -> +∞, Zero/Down -> largest finite.
1078        let huge = FBig::<mode::HalfEven, 2>::from_parts(IBig::ONE << 63, 0)
1079            .with_precision(p)
1080            .value();
1081        let up = huge.clone().with_rounding::<mode::Up>().exp();
1082        let zero = huge.clone().with_rounding::<mode::Zero>().exp();
1083        let down = huge.clone().with_rounding::<mode::Down>().exp();
1084        assert!(up.repr().is_infinite() && up.repr().sign() == Sign::Positive, "Up -> +∞");
1085        assert_eq!(zero.repr().significand(), &max_sig, "Zero -> largest finite significand");
1086        assert_eq!(zero.repr().exponent(), isize::MAX, "Zero -> largest finite exponent");
1087        assert_eq!(down.repr().significand(), &max_sig, "Down -> largest finite");
1088        assert_eq!(down.repr().exponent(), isize::MAX);
1089        assert!(up > zero, "Up(+∞) > largest finite");
1090
1091        // powi(-2, huge odd): negative overflow. Down -> -∞, Up -> largest finite negative.
1092        let odd = IBig::from(10_000_000_000_000_000_001_i128);
1093        let n_up = FBig::<mode::Up, 2>::from_parts(IBig::from(-2), 0)
1094            .with_precision(p)
1095            .value()
1096            .powi(odd.clone());
1097        let n_down = FBig::<mode::Down, 2>::from_parts(IBig::from(-2), 0)
1098            .with_precision(p)
1099            .value()
1100            .powi(odd.clone());
1101        assert!(
1102            n_down.repr().is_infinite() && n_down.repr().sign() == Sign::Negative,
1103            "Down -> -∞"
1104        );
1105        assert_eq!(
1106            n_up.repr().significand(),
1107            &(-max_sig.clone()),
1108            "Up -> largest finite negative significand"
1109        );
1110        assert_eq!(n_up.repr().exponent(), isize::MAX);
1111        assert_eq!(n_up.repr().sign(), Sign::Negative);
1112    }
1113
1114    // Overflow at unlimited precision panics: the largest finite is undefined (no precision cap),
1115    // so the directed endpoint can't be formed. Reached via `powi` with a positive exponent, which
1116    // skips the limited-precision assertion and lets the overflow reach `unwrap_fp`.
1117    #[test]
1118    #[should_panic(expected = "precision cannot be 0")]
1119    fn test_overflow_at_unlimited_precision_panics() {
1120        let base =
1121            FBig::<mode::Zero, 2>::from_repr(Repr::<2>::new(IBig::from(2), 0), Context::new(0));
1122        let _ = base.powi(IBig::from(10_000_000_000_000_000_000_i128));
1123    }
1124
1125    // Exponents past `i64` (bit length > `MAX_POWI_CHAIN_BITS`) can't use the squaring chain: for a
1126    // base near 1 the magnitude overflows the finite range mid-computation, and the chain's growing
1127    // working precision exhausts memory. The `exp(y·ln x)` fallback computes these without scaling
1128    // the working precision with the exponent's bit length, returning the correct directed endpoint.
1129    #[test]
1130    fn test_powi_huge_exponent_fallback() {
1131        let p = 53usize;
1132        let max_sig = (IBig::ONE << p) - IBig::ONE;
1133        // base = 1 + 2^-52 (just above 1); exponent 2^200 has bit length 201.
1134        let near1 = 0x3ff0_0000_0000_0001u64;
1135        let huge_pos = IBig::ONE << 200usize;
1136        let huge_neg = -(IBig::ONE << 200usize);
1137
1138        // positive base, positive huge exp -> positive overflow. Up -> +∞, Down -> largest finite.
1139        let up = FBig::<mode::Up, 2>::try_from(f64::from_bits(near1))
1140            .unwrap()
1141            .with_precision(p)
1142            .value()
1143            .powi(huge_pos.clone());
1144        let down = FBig::<mode::Down, 2>::try_from(f64::from_bits(near1))
1145            .unwrap()
1146            .with_precision(p)
1147            .value()
1148            .powi(huge_pos.clone());
1149        let he = FBig::<mode::HalfEven, 2>::try_from(f64::from_bits(near1))
1150            .unwrap()
1151            .with_precision(p)
1152            .value()
1153            .powi(huge_pos.clone());
1154        assert!(up.repr().is_infinite() && up.repr().sign() == Sign::Positive, "Up -> +∞");
1155        assert_eq!(down.repr().significand(), &max_sig, "Down -> largest finite");
1156        assert_eq!(down.repr().exponent(), isize::MAX);
1157        assert!(he.repr().is_infinite() && he.repr().sign() == Sign::Positive, "nearest -> +∞");
1158        assert!(up > down);
1159
1160        // positive base, negative huge exp -> underflow. Up -> smallest positive, Down -> +0.
1161        let u_up = FBig::<mode::Up, 2>::try_from(f64::from_bits(near1))
1162            .unwrap()
1163            .with_precision(p)
1164            .value()
1165            .powi(huge_neg.clone());
1166        let u_down = FBig::<mode::Down, 2>::try_from(f64::from_bits(near1))
1167            .unwrap()
1168            .with_precision(p)
1169            .value()
1170            .powi(huge_neg.clone());
1171        assert_eq!(u_up.repr().significand(), &IBig::from(1));
1172        assert_eq!(u_up.repr().exponent(), isize::MIN);
1173        assert!(u_down.repr().is_pos_zero());
1174        assert!(u_up > u_down);
1175
1176        // negative base near -1, huge exponent: sign follows the exponent's parity. The magnitude
1177        // overflows, so nearest reaches ±∞ with the parity sign.
1178        let neg_near1 = 0xbff0_0000_0000_0001u64;
1179        let even = huge_pos.clone();
1180        let odd = (IBig::ONE << 200usize) + IBig::ONE;
1181        let he_even = FBig::<mode::HalfEven, 2>::try_from(f64::from_bits(neg_near1))
1182            .unwrap()
1183            .with_precision(p)
1184            .value()
1185            .powi(even);
1186        let he_odd = FBig::<mode::HalfEven, 2>::try_from(f64::from_bits(neg_near1))
1187            .unwrap()
1188            .with_precision(p)
1189            .value()
1190            .powi(odd.clone());
1191        assert!(
1192            he_even.repr().is_infinite() && he_even.repr().sign() == Sign::Positive,
1193            "even exponent -> +∞"
1194        );
1195        assert!(
1196            he_odd.repr().is_infinite() && he_odd.repr().sign() == Sign::Negative,
1197            "odd exponent -> -∞"
1198        );
1199        // Down of a negative overflow rounds toward -∞.
1200        let down_odd = FBig::<mode::Down, 2>::try_from(f64::from_bits(neg_near1))
1201            .unwrap()
1202            .with_precision(p)
1203            .value()
1204            .powi(odd);
1205        assert!(
1206            down_odd.repr().is_infinite() && down_odd.repr().sign() == Sign::Negative,
1207            "Down(negative overflow) -> -∞"
1208        );
1209    }
1210
1211    // Directed `powi` on a tiny base with a large negative exponent: base ≈ -3.6e-5, exponent
1212    // -2^31. The result (≈2^3.17e10) is representable on 64-bit `isize` (MAX ≈ 9.2e18), so this
1213    // exercises the squaring chain (bit length 32 ≤ MAX_POWI_CHAIN_BITS) and must return a finite
1214    // value promptly — a regression guard for the chain path. On 32-bit `isize` (MAX ≈ 2.1e9) the
1215    // same result overflows and is short-circuited by the range guard, so the guard is 64-bit-only.
1216    #[cfg(target_pointer_width = "64")]
1217    #[test]
1218    fn test_powi_reproducer_small_base_representable() {
1219        let base_bits = 0xbf02e3ff24ffff1fu64;
1220        let exp = IBig::from(-(1i64 << 31));
1221        for p in [20usize, 50, 100, 500] {
1222            let v = FBig::<mode::HalfEven, 2>::try_from(f64::from_bits(base_bits))
1223                .unwrap()
1224                .with_precision(p)
1225                .value()
1226                .powi(exp.clone());
1227            assert!(!v.repr().is_infinite(), "finite at p={p}");
1228            assert_eq!(v.repr().sign(), Sign::Positive, "even exponent -> positive at p={p}");
1229            // magnitude ≈ 2^3.17e10, far from 1 — the chain computed the huge representable value.
1230            assert!(v.repr().exponent() > 1_000_000_000, "huge magnitude at p={p}");
1231        }
1232    }
1233
1234    // `powi(2, exp)` for `exp` just below `isize::MAX`: the result `2^exp` is representable (its
1235    // exponent is `exp ≤ isize::MAX`), so the range guard correctly does not short-circuit it and
1236    // the squaring chain computes it. The Ziv containment test then compares Reprs at that extreme
1237    // magnitude — `repr_cmp_same_base` used to do `exponent + digits` in plain `isize`, which
1238    // overflows near the ceiling and aborted (the raw-backend `backend_float_extremes` crash).
1239    #[test]
1240    fn test_powi_power_of_two_near_ceiling() {
1241        for offset in [1isize, 2, 60, 100, 1000] {
1242            let exp = IBig::from(isize::MAX - offset);
1243            let up = FBig::<mode::Up, 2>::from_parts(IBig::ONE, 1)
1244                .with_precision(53)
1245                .value()
1246                .powi(exp.clone());
1247            let down = FBig::<mode::Down, 2>::from_parts(IBig::ONE, 1)
1248                .with_precision(53)
1249                .value()
1250                .powi(exp.clone());
1251            // 2^exp is an exact power of two: significand 1 at exponent exp, identical under Up/Down.
1252            assert!(!up.repr().is_infinite(), "finite for offset {offset}");
1253            assert_eq!(up.repr().significand(), &IBig::from(1), "sig 1 for offset {offset}");
1254            assert_eq!(up.repr().exponent(), isize::MAX - offset, "exponent for offset {offset}");
1255            assert_eq!(down.repr().exponent(), isize::MAX - offset);
1256            assert!(!up.repr().is_infinite() && !down.repr().is_infinite());
1257        }
1258
1259        // Symmetric floor: `powi(2, -exp)` for `exp` just below `isize::MAX` gives `2^-exp`, whose
1260        // exponent sits just above `isize::MIN`. The containment test compares Reprs there too — the
1261        // saturating `cmp` shortcuts cover the floor as well as the ceiling (this is the negative-
1262        // exponent half of the range-handling TODO).
1263        for offset in [1isize, 2, 60, 100, 1000] {
1264            let exp = IBig::from(-(isize::MAX - offset));
1265            let up = FBig::<mode::Up, 2>::from_parts(IBig::ONE, 1)
1266                .with_precision(53)
1267                .value()
1268                .powi(exp.clone());
1269            let down = FBig::<mode::Down, 2>::from_parts(IBig::ONE, 1)
1270                .with_precision(53)
1271                .value()
1272                .powi(exp);
1273            assert!(!up.repr().is_infinite(), "finite for floor offset {offset}");
1274            assert_eq!(up.repr().significand(), &IBig::from(1), "sig 1 for floor offset {offset}");
1275            assert_eq!(up.repr().exponent(), -(isize::MAX - offset));
1276            assert!(!down.repr().is_infinite());
1277        }
1278    }
1279
1280    // `powi(2, isize::MAX)`: the result `2^isize::MAX` normalizes to significand 1 at the `+inf`
1281    // sentinel exponent, so it is genuine overflow. This used to panic — the squaring chain absorbed
1282    // the overflow into an infinity and the Ziv closure then choked on `res.ulp()` of an infinity.
1283    // Now the chain propagates the range error and `powi` returns the directed endpoint for every
1284    // mode. `isize::MAX` is the sentinel on both pointer widths, so this test is arch-independent.
1285    #[test]
1286    fn test_powi_exact_ceiling_overflow_directed() {
1287        let max_sig = |p: usize| (IBig::ONE << p) - IBig::ONE;
1288        let exp = IBig::from(isize::MAX);
1289        for p in [20usize, 50, 100, 500] {
1290            // Context layer: genuine overflow, positive sign.
1291            let ctx = Context::<mode::HalfEven>::new(p);
1292            let base = Repr::<2>::new(IBig::from(2), 0);
1293            assert_eq!(
1294                ctx.powi::<2>(&base, exp.clone()),
1295                Err(FpError::Overflow(Sign::Positive)),
1296                "Overflow at p={p}"
1297            );
1298
1299            // Convenience layer: directed endpoints (outward → +∞, inward → largest finite).
1300            let he = FBig::<mode::HalfEven, 2>::from_parts(IBig::ONE, 1)
1301                .with_precision(p)
1302                .value()
1303                .powi(exp.clone());
1304            let up = FBig::<mode::Up, 2>::from_parts(IBig::ONE, 1)
1305                .with_precision(p)
1306                .value()
1307                .powi(exp.clone());
1308            let down = FBig::<mode::Down, 2>::from_parts(IBig::ONE, 1)
1309                .with_precision(p)
1310                .value()
1311                .powi(exp.clone());
1312            let zero = FBig::<mode::Zero, 2>::from_parts(IBig::ONE, 1)
1313                .with_precision(p)
1314                .value()
1315                .powi(exp.clone());
1316            assert!(
1317                he.repr().is_infinite() && he.repr().sign() == Sign::Positive,
1318                "HalfEven -> +∞ at p={p}"
1319            );
1320            assert!(
1321                up.repr().is_infinite() && up.repr().sign() == Sign::Positive,
1322                "Up -> +∞ at p={p}"
1323            );
1324            assert_eq!(down.repr().significand(), &max_sig(p), "Down -> largest finite at p={p}");
1325            assert_eq!(down.repr().exponent(), isize::MAX, "Down exponent at p={p}");
1326            assert_eq!(zero.repr().significand(), &max_sig(p), "Zero -> largest finite at p={p}");
1327            assert!(up > down, "Up >= Down at p={p}");
1328        }
1329    }
1330
1331    // Underflow propagation through the chain: a tiny base `2^(isize::MIN/2)` squared reaches the
1332    // `-inf` sentinel exponent (`isize::MIN`) on the first squaring, so the chain underflows and
1333    // `powi` routes it to the directed endpoint instead of panicking. (Note `powi(2, -isize::MAX)` is
1334    // *not* underflow — `2^-isize::MAX` sits at exponent `isize::MIN+1`, still representable — so this
1335    // case uses a base whose square genuinely crosses the floor.) `isize::MIN/2` scales with the
1336    // pointer width, keeping the test arch-independent.
1337    #[test]
1338    fn test_powi_chain_underflow_propagates() {
1339        let half_floor = isize::MIN / 2;
1340        let ctx = Context::<mode::HalfEven>::new(53);
1341        let tiny = Repr::<2>::new(IBig::ONE, half_floor);
1342        assert_eq!(
1343            ctx.powi::<2>(&tiny, IBig::from(2)),
1344            Err(FpError::Underflow(Sign::Positive)),
1345            "base^2 underflows to the floor sentinel"
1346        );
1347
1348        // Convenience layer: directed endpoints (outward → smallest positive, inward/nearest → +0).
1349        let he = FBig::<mode::HalfEven, 2>::from_parts(IBig::ONE, half_floor)
1350            .with_precision(53)
1351            .value()
1352            .powi(IBig::from(2));
1353        let up = FBig::<mode::Up, 2>::from_parts(IBig::ONE, half_floor)
1354            .with_precision(53)
1355            .value()
1356            .powi(IBig::from(2));
1357        let down = FBig::<mode::Down, 2>::from_parts(IBig::ONE, half_floor)
1358            .with_precision(53)
1359            .value()
1360            .powi(IBig::from(2));
1361        assert!(he.repr().is_pos_zero(), "HalfEven -> +0");
1362        assert_eq!(up.repr().significand(), &IBig::from(1), "Up -> smallest positive");
1363        assert_eq!(up.repr().exponent(), isize::MIN, "Up exponent");
1364        assert!(down.repr().is_pos_zero(), "Down -> +0");
1365        assert!(up > down, "Up >= Down");
1366    }
1367
1368    // Significand != 1 and negative-base sign handling at the ceiling: the magnitude overflows just
1369    // the same and must propagate (not panic), with the overflow sign following base sign × parity.
1370    #[test]
1371    fn test_powi_significand_nonunit_ceiling() {
1372        let ctx = Context::<mode::HalfEven>::new(53);
1373        // base 3: 3^isize::MAX overflows with a positive sign.
1374        let base3 = Repr::<2>::new(IBig::from(3), 0);
1375        assert_eq!(
1376            ctx.powi::<2>(&base3, IBig::from(isize::MAX)),
1377            Err(FpError::Overflow(Sign::Positive)),
1378            "3^MAX overflows positive"
1379        );
1380        // base -2, odd exponent isize::MAX: (-2)^odd is negative -> Overflow(Negative).
1381        let neg2 = Repr::<2>::new(IBig::from(-2), 0);
1382        assert_eq!(
1383            ctx.powi::<2>(&neg2, IBig::from(isize::MAX)),
1384            Err(FpError::Overflow(Sign::Negative)),
1385            "(-2)^MAX overflows negative"
1386        );
1387    }
1388
1389    // Regression guard: a negative base with an *even* exponent just below the ceiling is
1390    // representable (positive, magnitude 2^(isize::MAX-1)) and must still compute to a finite value
1391    // — the overflow propagation must not over-broaden and treat near-ceiling representable results
1392    // as overflow. `isize::MAX - 1` is even on both 32- and 64-bit.
1393    #[test]
1394    fn test_powi_negative_base_even_exp_near_ceiling() {
1395        let exp = IBig::from(isize::MAX - 1);
1396        for p in [20usize, 50, 100, 500] {
1397            let v = FBig::<mode::HalfEven, 2>::try_from(-2.0f64)
1398                .unwrap()
1399                .with_precision(p)
1400                .value()
1401                .powi(exp.clone());
1402            assert!(!v.repr().is_infinite(), "finite at p={p}");
1403            assert_eq!(v.repr().sign(), Sign::Positive, "even exponent -> positive at p={p}");
1404            assert_eq!(v.repr().significand(), &IBig::from(1), "sig 1 at p={p}");
1405            assert_eq!(v.repr().exponent(), isize::MAX - 1, "exponent at p={p}");
1406        }
1407    }
1408
1409    // A sharp OOM regression needs an exponent gap large enough that 2^gap exceeds any
1410    // memory (gap ≳ 1e11), yet with floor(x/ln2) still fitting isize so the overflow
1411    // branch is not taken. That window only exists where isize is 64-bit: on 32-bit,
1412    // isize tops out at ~2.1e9 — below any OOM-inducing gap — so the overflow branch
1413    // always intervenes first. The fix itself (log2_bounds in round_fract) is
1414    // arch-independent; only this dedicated sharp test is 64-bit-only.
1415    #[test]
1416    fn test_exact_results_on_unlimited_precision() {
1417        // Regression test: values carrying precision 0 (unlimited) — produced by
1418        // `try_from(0.0)` and the `FBig::ONE`/`ZERO` constants — must still compute
1419        // their exact-result special cases instead of panicking in
1420        // assert_limited_precision before reaching the shortcut.
1421        type F = FBig<mode::HalfEven, 2>;
1422
1423        let zero = F::try_from(0.0_f64).unwrap();
1424        assert_eq!(zero.exp(), F::ONE);
1425        assert_eq!(zero.exp_m1(), F::ZERO);
1426        assert_eq!(zero.sqrt(), F::ZERO);
1427        assert_eq!(zero.ln_1p(), F::ZERO);
1428
1429        // -0.0 preserves its sign through exp_m1 and sqrt.
1430        let neg_zero = F::try_from(-0.0_f64).unwrap();
1431        assert!(neg_zero.exp_m1().repr().is_neg_zero());
1432        assert!(neg_zero.sqrt().repr().is_neg_zero());
1433
1434        // FBig::ONE carries unlimited precision; ln(1) = 0 is exact.
1435        assert_eq!(F::ONE.ln(), F::ZERO);
1436    }
1437
1438    #[test]
1439    fn test_powf_zero_base() {
1440        use crate::DBig;
1441        // powf with a float exponent returns the *positive* result on a zero base
1442        // (matching the common float-pow convention); use powi for the signed result.
1443        let ctx = Context::<mode::HalfEven>::new(53);
1444        // powf(-0, 2.0) = +0 (NOT -0)
1445        let r = ctx
1446            .powf::<2>(&Repr::<2>::neg_zero(), &Repr::new(2.into(), 0), None)
1447            .unwrap()
1448            .value();
1449        assert!(r.repr().is_pos_zero(), "expected +0");
1450        assert!(!r.repr().is_neg_zero(), "powf(-0, x) should be +0, not -0");
1451        // powf(0, -1) = +inf
1452        let r = ctx
1453            .powf::<2>(&Repr::<2>::zero(), &Repr::new((-1i32).into(), 0), None)
1454            .unwrap()
1455            .value();
1456        assert!(r.repr().is_infinite());
1457        assert_eq!(r.repr().sign(), Sign::Positive);
1458        // powi(-0, 3) = -0 (the sign-correct, integer-exponent variant)
1459        let r = ctx
1460            .powi::<2>(&Repr::<2>::neg_zero(), 3.into())
1461            .unwrap()
1462            .value();
1463        assert!(r.repr().is_neg_zero());
1464        let _ = DBig::ZERO;
1465    }
1466
1467    #[test]
1468    fn test_powf_integer_exponent() {
1469        use crate::DBig;
1470        let ctx = Context::<mode::HalfEven>::new(53);
1471        // integer-valued float exponent delegates to powi and supports a negative base (its sign
1472        // is fixed by the exponent's parity): (-5)^3 = -125.
1473        let neg_base = &Repr::<2>::new((-5).into(), 0);
1474        let exp3 = &Repr::<2>::new(3.into(), 0);
1475        let via_powf = ctx.powf::<2>(neg_base, exp3, None).unwrap().value();
1476        let via_powi = ctx.powi::<2>(neg_base, 3.into()).unwrap().value();
1477        assert_eq!(via_powf.repr(), via_powi.repr());
1478        assert_eq!(via_powf.repr().sign(), Sign::Negative);
1479
1480        // a non-integer exponent on a negative base is out of domain (no real value)
1481        let exp_half = &Repr::<2>::new(5.into(), -1); // 2.5
1482        assert_eq!(ctx.powf::<2>(neg_base, exp_half, None), Err(FpError::OutOfDomain));
1483
1484        // positive base, integer exponent: also routes through powi
1485        let pos_base = &Repr::<2>::new(3.into(), 0);
1486        let exp4 = &Repr::<2>::new(4.into(), 0);
1487        let r = ctx.powf::<2>(pos_base, exp4, None).unwrap().value();
1488        assert_eq!(r.repr(), ctx.powi::<2>(pos_base, 4.into()).unwrap().value().repr());
1489        let _ = DBig::ZERO;
1490    }
1491
1492    /// The `exp_ball` input-error fold must scale by the *result's* magnitude, not just by the
1493    /// input radius. For a large negative argument `exp(x)` is tiny, so an absolute fold
1494    /// (`rad_x`, i.e. a factor clamped to 1) over-estimates the error by `e^{−x}` — hundreds of
1495    /// digits. The radius then dwarfs the value and Ziv can only certify by growing the working
1496    /// precision past `|x|/log_B e`, which is what made `powf` with a large `|y·ln x|` take
1497    /// seconds per call.
1498    #[test]
1499    fn exp_ball_radius_scales_with_result_magnitude_for_negative_args() {
1500        type F = FBig<mode::HalfEven, 10>;
1501        let ctx = Context::<mode::HalfEven>::new(10);
1502        // mid = −6000 at precision 10 (ulp = 1e-6), rad = 10 ulps ⇒ true arg = −6000 ± 1e-5.
1503        let mid = F::from_parts(IBig::from(-6000000000i64), -6)
1504            .with_precision(10)
1505            .value();
1506        let rad = ulps::<10>(&mid.repr, 10, 10);
1507        let x = Ball::<10>::with_error(mid.into_repr(), rad);
1508        let r = ctx.exp_ball::<10>(&x, 10, None).unwrap();
1509
1510        // True contribution: e^{−6000}·(e^{1e-5} − 1) ≈ 1e-2611 against a result e^{−6000} ≈
1511        // 1.7e-2606 — a ratio of ~1/10⁴. Asserting the radius stays under 1/100 of the result's
1512        // magnitude leaves ~170× margin, while the absolute fold this test pins down puts the
1513        // radius *above* the result by ~10^2582. (A ulp-count bound is avoided on purpose: `ulps`
1514        // takes its multiplier as a `Word`, which `force_bits="16"` narrows to 16 bits.)
1515        assert!(
1516            r.rad.mul(&crate::mag::Mag::from_word(100)) <= crate::mag::Mag::from_repr(&r.mid),
1517            "radius {:?} is not scaled by the result magnitude (result {:?})",
1518            r.rad,
1519            r.mid
1520        );
1521    }
1522
1523    /// End-to-end pin for the same defect: `powf` whose exponentiation drives the `exp` argument
1524    /// far negative must certify on the first Ziv attempt. With an absolute input-error fold the
1525    /// radius never reaches the result's ulp scale and the loop burns ~9 retries at a working
1526    /// precision of thousands of digits (≈1.5 s at this precision, vs microseconds).
1527    // Retry-count assertions read the `thread_local` counter, which only exists under `std`.
1528    #[cfg(feature = "std")]
1529    #[test]
1530    fn powf_large_negative_exp_certifies_first_attempt() {
1531        type F = FBig<mode::HalfEven, 10>;
1532        let ctx = Context::<mode::HalfEven>::new(16);
1533        // base = 7.028…e71 (76 digits), exp = −84.91 ⇒ y·ln(base) ≈ −14035, result ≈ 1e-6096.
1534        let base = F::from_parts(
1535            IBig::from_str_radix(
1536                "7028223021191846562494387621240260047617927946605687951670131559429803281481",
1537                10,
1538            )
1539            .unwrap(),
1540            -4,
1541        );
1542        let exp = F::from_parts(IBig::from(-8491i64), -2); // −84.91
1543        crate::ziv_retries_reset();
1544        let _ = ctx.powf::<10>(base.repr(), exp.repr(), None).unwrap();
1545        assert_eq!(
1546            crate::ziv_retries(),
1547            0,
1548            "powf with a large |y·ln x| should certify on the first attempt"
1549        );
1550    }
1551
1552    // The `Bⁿ` powering chain's radius slack used to cost one systematic Ziv retry on
1553    // non-power-of-two bases at *every* precision (`pow_chain_guard` now charges the chain
1554    // length to the initial guard). Pin two measured retrying points (DBig `exp 1` and base-3
1555    // `exp 2`/`1/3` across the sweep) to first-attempt certification.
1556    #[cfg(feature = "std")]
1557    #[test]
1558    fn exp_certifies_first_attempt_with_powering_chain() {
1559        // DBig exp(1) @ 6 digits — the smallest measured retrying precision.
1560        let ctx = Context::<mode::HalfEven>::new(6);
1561        crate::ziv_retries_reset();
1562        let _ = ctx.exp::<10>(&Repr::<10>::one(), None).unwrap();
1563        assert_eq!(crate::ziv_retries(), 0, "DBig exp(1) @6 should certify on the first attempt");
1564
1565        // base-3 exp(2) @ 12 trits.
1566        let ctx = Context::<mode::HalfEven>::new(12);
1567        crate::ziv_retries_reset();
1568        let _ = ctx.exp::<3>(&Repr::<3>::new(2.into(), 0), None).unwrap();
1569        assert_eq!(
1570            crate::ziv_retries(),
1571            0,
1572            "base-3 exp(2) @12 should certify on the first attempt"
1573        );
1574    }
1575
1576    // The powf path (`pow_exp_log`) folds `y·ln x`'s radius through the same powering chain
1577    // against a thin `+10` guard — the one base-2 case the charge covers unconditionally
1578    // (1.5^0.75 @500b and @2000b, 16^0.75 @2000b each retried once).
1579    #[cfg(feature = "std")]
1580    #[test]
1581    fn powf_certifies_first_attempt_base2() {
1582        let ctx = Context::<mode::HalfEven>::new(500);
1583        crate::ziv_retries_reset();
1584        let _ = ctx
1585            .powf::<2>(&Repr::<2>::new(3.into(), -1), &Repr::<2>::new(3.into(), -2), None)
1586            .unwrap();
1587        assert_eq!(
1588            crate::ziv_retries(),
1589            0,
1590            "powf(1.5, 0.75) @500b should certify on the first attempt"
1591        );
1592    }
1593
1594    #[test]
1595    fn exp_ball_bounds_propagated_input_error() {
1596        use dashu_base::{Abs, AbsOrd};
1597        // The input ball's error must be amplified by e^{x+rad} in the result radius: rad has
1598        // to cover rad_x·e^{x+rad_x}. Regression for the missing magnitude factor in
1599        // `exp_ball`'s input-error fold (the old ulp-domain code dropped the significand
1600        // factor and let Ziv certify an interval that did not contain the true value).
1601        type F = FBig<mode::HalfEven, 10>;
1602        let ctx = Context::<mode::HalfEven>::new(10);
1603        // mid = 0.5 at precision 10 (ulp = 1e-10), rad = 10 ulps ⇒ true arg = 0.5000000010.
1604        let mid = F::from_parts(IBig::from(5000000000i64), -10)
1605            .with_precision(10)
1606            .value();
1607        let rad = ulps::<10>(&mid.repr, 10, 10);
1608        let x = Ball::<10>::with_error(mid.into_repr(), rad);
1609        let r = ctx.exp_ball::<10>(&x, 10, None).unwrap();
1610        let true_arg = F::from_parts(IBig::from(5000000010i64), -10)
1611            .with_precision(0)
1612            .value();
1613        let exp_true = true_arg
1614            .with_precision(60)
1615            .value()
1616            .exp()
1617            .with_precision(0)
1618            .value();
1619        let mid_f = F::new(r.mid.clone(), Context::<mode::HalfEven>::new(0));
1620        let diff = (mid_f - exp_true).abs();
1621        let bound = F::new(r.rad.to_repr::<10>(), Context::<mode::HalfEven>::new(0));
1622        assert!(diff.abs_cmp(&bound).is_le(), "exp_ball: |mid − true| = {diff} > rad = {bound}");
1623    }
1624
1625    #[test]
1626    fn exp_generic_base_matches_oracle() {
1627        // exp at a generic (uncached) base exercises `ln_base_ball`'s mechanical-radius path for
1628        // ln(B) — the hard-coded `8`-ulp bound would under-bind a generic base's atanh-series
1629        // error (which is ~series-terms ulps), silently unsounding the reduction.
1630        type F3 = FBig<mode::HalfEven, 3>;
1631        for x in [1i64, 2, 3, 5] {
1632            let x = F3::from_parts(IBig::from(x), 0);
1633            let ctx = Context::<mode::HalfEven>::new(30);
1634            let got = ctx.exp::<3>(&x.repr, None).unwrap().value();
1635            let oracle = Context::<mode::HalfEven>::new(90)
1636                .exp::<3>(&x.repr, None)
1637                .unwrap()
1638                .value();
1639            let want = ctx.repr_round_ref(&oracle.repr).value();
1640            assert_eq!(got.repr, want, "exp({x:?}) at base 3 p=30: got {got:?}, want {want:?}");
1641        }
1642    }
1643}