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