1use dashu_base::{Approximation, Sign, SquareRoot, SquareRootRem, UnsignedAbs};
2use dashu_int::IBig;
3
4use crate::{
5 error::{assert_finite, assert_limited_precision, panic_root_negative},
6 fbig::FBig,
7 repr::{Context, Repr, Word},
8 round::{Round, Rounded},
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.sqrt(self.repr()).value()
17 }
18}
19
20impl<R: Round> Context<R> {
21 pub fn sqrt<const B: Word>(&self, x: &Repr<B>) -> Rounded<FBig<R, B>> {
42 assert_finite(x);
43 assert_limited_precision(self.precision);
44 if x.sign() == Sign::Negative {
45 panic_root_negative()
46 }
47
48 let digits = x.digits() as isize;
50 let shift = self.precision as isize * 2 - (digits & 1) + (x.exponent & 1) - digits;
51 let (signif, low, low_digits) = if shift > 0 {
52 (shl_digits::<B>(&x.significand, shift as usize), IBig::ZERO, 0)
53 } else {
54 let shift = (-shift) as usize;
55 let (hi, lo) = split_digits_ref::<B>(&x.significand, shift);
56 (hi, lo, shift)
57 };
58
59 let (root, rem) = signif.unsigned_abs().sqrt_rem();
60 let root = Sign::Positive * root;
61 let exp = (x.exponent - shift) / 2;
62
63 let res = if rem.is_zero() {
64 Approximation::Exact(root)
65 } else {
66 let adjust = R::round_low_part(&root, Sign::Positive, || {
67 (Sign::Positive * rem)
68 .cmp(&root)
69 .then_with(|| (low * 4u8).cmp(&Repr::<B>::BASE.pow(low_digits).into()))
70 });
71 Approximation::Inexact(root + adjust, adjust)
72 };
73 res.map(|signif| Repr::new(signif, exp))
74 .and_then(|v| self.repr_round(v))
75 .map(|v| FBig::new(v, *self))
76 }
77}
78
79