Skip to main content

dashu_float/
root.rs

1use dashu_base::{Approximation, CubicRoot, Sign, SquareRoot, SquareRootRem, UnsignedAbs};
2use dashu_int::{IBig, UBig};
3
4use crate::{
5    error::{assert_limited_precision, panic_root_zeroth, FpError, FpResult},
6    fbig::FBig,
7    repr::{Context, Repr, Word},
8    round::Round,
9    utils::{shl_digits, split_digits_ref},
10};
11
12impl<R: Round, const B: Word> SquareRoot for FBig<R, B> {
13    type Output = Self;
14    #[inline]
15    fn sqrt(&self) -> Self {
16        self.context.unwrap_fp(self.context.sqrt(self.repr()))
17    }
18}
19
20impl<R: Round, const B: Word> CubicRoot for FBig<R, B> {
21    type Output = Self;
22    #[inline]
23    fn cbrt(&self) -> Self {
24        self.context.unwrap_fp(self.context.cbrt(self.repr()))
25    }
26}
27
28impl<R: Round, const B: Word> FBig<R, B> {
29    /// Calculate the square root of the floating point number.
30    ///
31    /// # Panics
32    ///
33    /// Panics if the precision is unlimited.
34    #[inline]
35    pub fn sqrt(&self) -> Self {
36        self.context.unwrap_fp(self.context.sqrt(&self.repr))
37    }
38
39    /// Calculate the nth root of the floating point number.
40    ///
41    /// When `n` is large the computation can be expensive — the significand is
42    /// padded to `n · precision` digits before the integer root is taken, and
43    /// the integer Newton iteration works with numbers of that size. For large
44    /// `n` consider [`powf`][`FBig::powf`] with a rational exponent `1 / n`
45    /// as a faster approximate alternative.
46    ///
47    /// # Examples
48    ///
49    /// ```
50    /// # use core::str::FromStr;
51    /// # use dashu_base::ParseError;
52    /// # use dashu_float::DBig;
53    /// let a = DBig::from_str("16")?;
54    /// assert_eq!(a.nth_root(4), DBig::from_str("2")?);
55    /// # Ok::<(), ParseError>(())
56    /// ```
57    ///
58    /// # Panics
59    ///
60    /// Panics if `n` is zero, or if `n` is even and the number is negative.
61    #[inline]
62    pub fn nth_root(&self, n: usize) -> Self {
63        self.context
64            .unwrap_fp(self.context.nth_root(n, self.repr()))
65    }
66}
67
68impl<R: Round> Context<R> {
69    /// Calculate the square root of the floating point number.
70    ///
71    /// # Examples
72    ///
73    /// ```
74    /// # use core::str::FromStr;
75    /// # use dashu_base::ParseError;
76    /// # use dashu_float::DBig;
77    /// use dashu_base::Approximation::*;
78    /// use dashu_float::{Context, round::{mode::HalfAway, Rounding::*}};
79    ///
80    /// let context = Context::<HalfAway>::new(2);
81    /// let a = DBig::from_str("1.23")?;
82    /// assert_eq!(context.sqrt(&a.repr()), Ok(Inexact(DBig::from_str("1.1")?, NoOp)));
83    /// # Ok::<(), ParseError>(())
84    /// ```
85    ///
86    /// # Panics
87    ///
88    /// Panics if the precision is unlimited.
89    pub fn sqrt<const B: Word>(&self, x: &Repr<B>) -> FpResult<FBig<R, B>> {
90        if x.is_infinite() {
91            return Err(FpError::InfiniteInput);
92        }
93        assert_limited_precision(self.precision);
94        if x.significand.is_zero() {
95            // sqrt(+0) = +0, sqrt(-0) = -0 (preserve the sign of zero)
96            return Ok(Approximation::Exact(FBig::new(x.clone(), *self)));
97        }
98        if x.sign() == Sign::Negative {
99            return Err(FpError::OutOfDomain);
100        }
101
102        // adjust the signifcand so that the exponent is even
103        let digits = x.digits() as isize;
104        let shift = self.precision as isize * 2 - (digits & 1) + (x.exponent & 1) - digits;
105        let (signif, low, low_digits) = if shift > 0 {
106            (shl_digits::<B>(&x.significand, shift as usize), IBig::ZERO, 0)
107        } else {
108            let shift = (-shift) as usize;
109            let (hi, lo) = split_digits_ref::<B>(&x.significand, shift);
110            (hi, lo, shift)
111        };
112
113        let (root, rem) = signif.unsigned_abs().sqrt_rem();
114        let root = Sign::Positive * root;
115        let exp = (x.exponent - shift) / 2;
116
117        let res = if rem.is_zero() {
118            Approximation::Exact(root)
119        } else {
120            let adjust = R::round_low_part(&root, Sign::Positive, || {
121                (Sign::Positive * rem)
122                    .cmp(&root)
123                    .then_with(|| (low * 4u8).cmp(&Repr::<B>::BASE.pow(low_digits).into()))
124            });
125            Approximation::Inexact(root + adjust, adjust)
126        };
127        Ok(res
128            .map(|signif| Repr::new(signif, exp))
129            .and_then(|v| self.repr_round(v))
130            .map(|v| FBig::new(v, *self)))
131    }
132
133    /// Calculate the cubic root of the floating point number.
134    ///
135    /// # Examples
136    ///
137    /// ```
138    /// # use core::str::FromStr;
139    /// # use dashu_base::ParseError;
140    /// # use dashu_float::DBig;
141    /// use dashu_base::Approximation::*;
142    /// use dashu_float::{Context, round::{mode::HalfAway, Rounding::*}};
143    ///
144    /// let context = Context::<HalfAway>::new(2);
145    /// let a = DBig::from_str("8")?;
146    /// assert_eq!(context.cbrt(&a.repr()), Ok(Exact(DBig::from_str("2")?)));
147    /// # Ok::<(), ParseError>(())
148    /// ```
149    ///
150    /// # Panics
151    ///
152    /// Panics if the precision is unlimited.
153    #[inline]
154    pub fn cbrt<const B: Word>(&self, x: &Repr<B>) -> FpResult<FBig<R, B>> {
155        self.nth_root(3, x)
156    }
157
158    /// Calculate the nth root of the floating point number.
159    ///
160    /// # Examples
161    ///
162    /// ```
163    /// # use core::str::FromStr;
164    /// # use dashu_base::ParseError;
165    /// # use dashu_float::DBig;
166    /// use dashu_base::Approximation::*;
167    /// use dashu_float::{Context, round::{mode::HalfAway, Rounding::*}};
168    ///
169    /// let context = Context::<HalfAway>::new(2);
170    /// let a = DBig::from_str("27")?;
171    /// assert_eq!(context.nth_root(3, &a.repr()), Ok(Exact(DBig::from_str("3")?)));
172    /// # Ok::<(), ParseError>(())
173    /// ```
174    ///
175    /// # Panics
176    ///
177    /// Panics if `n` is zero, if the precision is unlimited, or if `n` is even and `x` is negative.
178    pub fn nth_root<const B: Word>(&self, n: usize, x: &Repr<B>) -> FpResult<FBig<R, B>> {
179        if x.is_infinite() {
180            return Err(FpError::InfiniteInput);
181        }
182        assert_limited_precision(self.precision);
183        if n == 0 {
184            panic_root_zeroth()
185        }
186        debug_assert!(n < isize::MAX as usize);
187        let sign = x.sign();
188        if sign == Sign::Negative && n % 2 == 0 {
189            return Err(FpError::OutOfDomain);
190        }
191        if n == 1 {
192            return Ok(self.repr_round_ref(x).map(|v| FBig::new(v, *self)));
193        }
194        if x.significand.is_zero() {
195            // UBig::ZERO.nth_root(n) erroneously returns ONE, so short-circuit here.
196            // An even root of -0 already errored above, so reaching here the sign is
197            // preserved: odd root of ±0 is ±0.
198            return Ok(Approximation::Exact(FBig::new(x.clone(), *self)));
199        }
200
201        // operate on the magnitude so that shifting/splitting keep a clean sign;
202        // the original sign is re-applied to the result at the end.
203        let xmag: IBig = if sign == Sign::Negative {
204            -&x.significand
205        } else {
206            x.significand.clone()
207        };
208
209        // adjust the significand so that the exponent is divisible by n and the
210        // significand carries at least n*precision digits (required for rounding)
211        let digits = x.digits() as isize;
212        let r = (x.exponent + digits).rem_euclid(n as isize);
213        let shift = n as isize * self.precision as isize - digits + r;
214        let (signif, low, low_digits) = if shift > 0 {
215            (shl_digits::<B>(&xmag, shift as usize), IBig::ZERO, 0)
216        } else {
217            let shift = (-shift) as usize;
218            let (hi, lo) = split_digits_ref::<B>(&xmag, shift);
219            (hi, lo, shift)
220        };
221
222        let mag: UBig = signif.unsigned_abs();
223        let root: UBig = mag.nth_root(n);
224        let rem: UBig = &mag - root.clone().pow(n);
225        let exp = (x.exponent - shift) / n as isize;
226
227        let result_sign = if sign == Sign::Negative {
228            Sign::Negative
229        } else {
230            Sign::Positive
231        };
232        let signed_root: IBig = result_sign * root.clone();
233
234        let res = if rem.is_zero() && low.is_zero() {
235            Approximation::Exact(signed_root)
236        } else {
237            let adjust = R::round_low_part(&signed_root, result_sign, || {
238                // The true value is (mag + low / BASE^low_digits)^(1/n) and
239                // root = floor(mag^(1/n)); its fractional part is compared to 1/2.
240                // frac < 1/2  <=>  2^n * full < (2*root + 1)^n * BASE^low_digits,
241                // where full = mag * BASE^low_digits + low (the full significand).
242                let base_pow = Repr::<B>::BASE.pow(low_digits);
243                let full = &mag * &base_pow + low.unsigned_abs();
244                let lhs = full << n;
245                let rhs = ((root.clone() << 1) + UBig::from_word(1)).pow(n) * base_pow;
246                lhs.cmp(&rhs)
247            });
248            Approximation::Inexact(signed_root.clone() + adjust, adjust)
249        };
250        Ok(res
251            .map(|signif| Repr::new(signif, exp))
252            .and_then(|v| self.repr_round(v))
253            .map(|v| FBig::new(v, *self)))
254    }
255}
256
257impl<R: Round> Context<R> {
258    /// Compute `sqrt(a² + b²)` without spurious overflow/underflow.
259    ///
260    /// This is the overflow-safe scaled sum-of-squares: the larger-magnitude operand is never
261    /// squared. Writing `m = max(|a|, |b|)` and `r = min(|a|,|b|) / m` (so `|r| ≤ 1`), the result is
262    /// `m · sqrt(1 + r²)`, where `1 + r² ∈ [1, 2]` cannot overflow. The final `m · sqrt(1 + r²)`
263    /// overflows only when the true result genuinely exceeds the exponent range (reported as
264    /// [`FpError::Overflow`]). `hypot(±inf, ·) = +inf`, `hypot(0, 0) = +0`.
265    ///
266    /// This is a field-arithmetic-class op (no constant cache), like `sqrt`/`atan2`.
267    ///
268    /// # Panics
269    ///
270    /// Panics if the precision is unlimited.
271    pub fn hypot<const B: Word>(&self, a: &Repr<B>, b: &Repr<B>) -> FpResult<FBig<R, B>> {
272        if a.is_infinite() || b.is_infinite() {
273            return Ok(Approximation::Exact(FBig::new(Repr::infinity(), *self)));
274        }
275        assert_limited_precision(self.precision);
276        if a.significand.is_zero() && b.significand.is_zero() {
277            return Ok(Approximation::Exact(FBig::new(Repr::zero(), *self)));
278        }
279
280        let guard = crate::utils::ceil_usize(<usize as dashu_base::EstimatedLog2>::log2_est(
281            &self.precision,
282        )) + 10;
283        let gctx = Context::<R>::new(self.precision + guard);
284
285        // magnitudes, ordered large >= small (both finite, not both zero here)
286        let a_mag = if a.sign() == Sign::Negative {
287            -a.clone()
288        } else {
289            a.clone()
290        };
291        let b_mag = if b.sign() == Sign::Negative {
292            -b.clone()
293        } else {
294            b.clone()
295        };
296        let (large, small) = if a_mag.cmp(&b_mag).is_ge() {
297            (a_mag, b_mag)
298        } else {
299            (b_mag, a_mag)
300        };
301
302        if small.significand.is_zero() {
303            // hypot(x, 0) = |x|; `large` is already a magnitude
304            return Ok(gctx.repr_round_ref(&large).map(|v| FBig::new(v, *self)));
305        }
306
307        // r = small / large ∈ [0, 1]; 1 + r² ∈ [1, 2] (no overflow); result = large · sqrt(1+r²)
308        let r = gctx.div(&small, &large)?.value();
309        let r2 = gctx.sqr(r.repr())?.value();
310        let sum = gctx.add(&Repr::one(), r2.repr())?.value();
311        let root = gctx.sqrt(sum.repr())?.value();
312        let result = gctx.mul(&large, root.repr())?.value();
313        Ok(result.with_precision(self.precision))
314    }
315}
316
317impl<R: Round, const B: Word> FBig<R, B> {
318    /// Compute `sqrt(self² + other²)` without spurious overflow/underflow.
319    ///
320    /// The result precision is `max(self.precision(), other.precision())`. See
321    /// [`Context::hypot`] for the overflow-safety strategy.
322    ///
323    /// # Examples
324    ///
325    /// ```
326    /// # use core::str::FromStr;
327    /// # use dashu_base::ParseError;
328    /// # use dashu_float::DBig;
329    /// let a = DBig::from_str("3")?;
330    /// let b = DBig::from_str("4")?;
331    /// assert_eq!(a.hypot(&b), DBig::from_str("5")?);
332    /// # Ok::<(), ParseError>(())
333    /// ```
334    ///
335    /// # Panics
336    ///
337    /// Panics if the precision is unlimited.
338    #[inline]
339    pub fn hypot(&self, other: &Self) -> Self {
340        let context = Context::max(self.context, other.context);
341        context.unwrap_fp(context.hypot(&self.repr, &other.repr))
342    }
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348    use crate::round::mode;
349
350    #[test]
351    #[should_panic]
352    fn test_fbig_sqrt_negative_panics() {
353        // sqrt(-1) is out of domain; the FBig layer panics.
354        let neg_one = FBig::<mode::HalfEven>::try_from(-1.0f64).unwrap();
355        let _ = neg_one.sqrt();
356    }
357
358    #[test]
359    fn test_hypot_pythagorean() {
360        let ctx = Context::<mode::HalfEven>::new(53);
361        let mk = |v: i32| Repr::<2>::new(v.into(), 0);
362        // hypot(3, 4) = 5
363        let r = ctx.hypot(&mk(3), &mk(4)).unwrap().value();
364        assert_eq!(r.repr().significand(), &5.into());
365        // hypot(5, 0) = 5
366        let r = ctx.hypot(&mk(5), &mk(0)).unwrap().value();
367        assert_eq!(r.repr().significand(), &5.into());
368        // hypot(0, 0) = 0
369        let r = ctx.hypot(&mk(0), &mk(0)).unwrap().value();
370        assert!(r.repr().is_pos_zero());
371        // hypot(inf, x) = +inf
372        let r = ctx.hypot(&Repr::infinity(), &mk(3)).unwrap().value();
373        assert!(r.repr().is_infinite());
374        assert_eq!(r.repr().sign(), Sign::Positive);
375    }
376
377    #[test]
378    fn test_hypot_no_spurious_overflow() {
379        // a value whose square would collide with the +inf sentinel exponent, but whose
380        // hypot is itself representable: hypot(a, 0) = |a| must not overflow via a².
381        let ctx = Context::<mode::HalfEven>::new(53);
382        // exponent near isize::MAX/2 so that a² would overflow, but |a| is fine
383        let a = Repr::<2>::new(IBig::from(3), isize::MAX / 2);
384        let r = ctx.hypot(&a, &Repr::<2>::zero()).unwrap().value();
385        assert_eq!(r.repr().exponent(), isize::MAX / 2);
386    }
387}