Skip to main content

malachite_float/float/arithmetic/
root.rs

1// Copyright © 2026 Mikhail Hogrefe
2//
3// Uses code adopted from the GNU MPFR Library.
4//
5//      Copyright 2005-2025 Free Software Foundation, Inc.
6//
7//      Contributed by the AriC and Caramba projects, INRIA.
8//
9// This file is part of Malachite.
10//
11// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
12// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
13// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
14
15use crate::InnerFloat::{Infinity, NaN, Zero};
16use crate::{Float, emulate_float_to_float_fn, emulate_rational_to_float_fn, float_nan};
17use core::cmp::Ordering::{self, *};
18use malachite_base::fail_on_untested_path;
19use malachite_base::num::arithmetic::traits::{
20    Abs, CeilingLogBase2, CheckedRoot, DivRound, DivisibleBy, IsPowerOf2, Parity, Reciprocal, Root,
21    RootAssign, RootRem, Sign,
22};
23use malachite_base::num::basic::floats::PrimitiveFloat;
24use malachite_base::num::basic::integers::PrimitiveInt;
25use malachite_base::num::basic::traits::One;
26use malachite_base::num::comparison::traits::PartialOrdAbs;
27use malachite_base::num::conversion::traits::{ExactFrom, RoundingFrom};
28use malachite_base::num::logic::traits::SignificantBits;
29use malachite_base::rounding_modes::RoundingMode::{self, *};
30use malachite_nz::natural::Natural;
31use malachite_nz::natural::arithmetic::float_extras::float_can_round;
32use malachite_nz::platform::Limb;
33use malachite_q::Rational;
34
35// For roots of order above this threshold, x^(1/k) is computed as exp(ln|x|/k) rather than by an
36// integer root of the scaled significand. This is the k > 100 threshold from root.c, MPFR 4.3.0.
37const HIGH_K_THRESHOLD: u64 = 100;
38
39// Decides an `Exact`-rounding-mode root exactly: x^(1/k) is exactly representable iff, writing |x|
40// = m * 2^e with m odd, e is divisible by k and m is a perfect kth power. Panics if the root is
41// inexact; otherwise returns it, rounded (exactly) to `prec` bits.
42fn root_u_exact(x: &Float, k: u64, prec: u64) -> (Float, Ordering) {
43    let m = x.significand_ref().unwrap();
44    let nu = m.trailing_zeros().unwrap();
45    let m_odd = m >> nu;
46    let e =
47        i128::from(x.get_exponent().unwrap()) - i128::from(m.significant_bits()) + i128::from(nu);
48    let root = Float::from_natural_prec_round(
49        (&m_odd).checked_root(k).expect("Inexact root"),
50        prec,
51        Exact,
52    )
53    .0 << e.div_round(i128::from(k), Exact).0;
54    (if x.is_sign_negative() { -root } else { root }, Equal)
55}
56
57// The integer-root path for 2 <= k <= 100: scale the significand m so that its integer kth root has
58// exactly n = prec (+ 1 for `Nearest`) bits, take the root, and round.
59//
60// This is mpfr_rootn_ui from root.c, MPFR 4.3.0, where the input is finite, nonzero, not a singular
61// value, |x| != 1, x is negative only for odd k, and 2 <= k <= 100 -- with one improvement adopted
62// from mpfr_cbrt (cbrt.c, MPFR 4.3.0) and generalized from k = 3 to any k: when m has more than k *
63// n bits, it is truncated rather than used in full. Any rounding breakpoint at precision n
64// (including the `Nearest` midpoints, since n already includes the round bit) has n significant
65// bits, so its kth power has at most k * n bits; bits of m below that can never move the root
66// across a breakpoint, and only need to be folded into the inexact flag. This makes the root's cost
67// independent of the input precision. (mpfr_rootn_ui itself keeps all of m.)
68fn root_u_integer(x: &Float, k: u64, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
69    let negative = x.is_sign_negative();
70    // x = m * 2^e
71    let mut m = x.significand_ref().unwrap().clone();
72    let mut e = i128::from(x.get_exponent().unwrap()) - i128::from(m.significant_bits());
73    let ki = i128::from(k);
74    let r = e.rem_euclid(ki); // r = e mod k with 0 <= r < k
75    // For rounding to nearest, we want the round bit to be in the root.
76    let n = i128::from(prec) + i128::from(rm == Nearest);
77    let size_m = i128::from(m.significant_bits());
78    // Shift m by t = k * f + r bits (leftwards for positive t, with truncation for negative t) so
79    // that the root of m has exactly n bits: we want k * (n - 1) + 1 <= size_m + t <= k * n, so f =
80    // floor((k * n - size_m - r) / k).
81    let t = (ki * n - size_m - r).div_euclid(ki) * ki + r;
82    let mut inexact = false;
83    if t >= 0 {
84        m <<= u64::exact_from(t);
85    } else {
86        // Truncate, folding the dropped bits into the inexact flag. If any dropped bit is nonzero,
87        // the true root cannot be exactly representable at n bits either: an exact root s with at
88        // most n bits would make x = s^k * 2^(k * e') need at most k * n significant bits.
89        let cut = u64::exact_from(-t);
90        inexact = m.trailing_zeros().unwrap() < cut;
91        m >>= cut;
92    }
93    e -= t;
94    // Invariant: x = m * 2^e (up to truncated bits), with e divisible by k.
95    let (mut root, rem) = m.root_rem(k);
96    inexact = inexact || rem != 0u32;
97    // If the root has more than n bits, flush the low sh2 bits into the inexact flag. (The size
98    // invariant above makes this unreachable: m has between k * (n - 1) + 1 and k * n bits, so its
99    // kth root has exactly n bits. It is kept as a safeguard, mirroring mpfr_rootn_ui.)
100    let size_root = root.significant_bits();
101    let n = u64::exact_from(n);
102    if size_root > n {
103        fail_on_untested_path(
104            "root_u_integer, root wider than n: the truncation above sizes m so that its root has \
105             exactly n bits",
106        );
107        let sh2 = size_root - n;
108        inexact = inexact || root.trailing_zeros().unwrap() < sh2;
109        root >>= sh2;
110        e += i128::from(sh2) * ki;
111    }
112    let mut o = Equal;
113    if inexact {
114        assert_ne!(rm, Exact, "Inexact root");
115        // Rounding modes are inverted for negative x, since the rounding decision below is made on
116        // the magnitude.
117        let rm_abs = if negative { -rm } else { rm };
118        o = if rm_abs == Ceiling || rm_abs == Up || (rm_abs == Nearest && root.odd()) {
119            root += Natural::ONE;
120            Greater
121        } else {
122            Less
123        };
124    }
125    // Either o is not `Equal` and the conversion is exact, or o is `Equal` and the conversion
126    // rounds only when rm is `Nearest` and the exact root has n = prec + 1 bits (a midpoint).
127    let (y, o2) = Float::from_natural_prec(root, prec);
128    debug_assert!(o == Equal || o2 == Equal);
129    if o == Equal {
130        o = o2;
131    }
132    // The result's exponent is about EXP(x) / k, always within the exponent range for k >= 2, so
133    // the shift is exact and cannot overflow or underflow.
134    let y = y << e.div_round(ki, Exact).0;
135    if negative { (-y, o.reverse()) } else { (y, o) }
136}
137
138// The large-k path: compute x^(1/k) as exp(ln|x|/k), with a Ziv loop and explicit detection of
139// exact and midpoint results (which the Ziv loop could never certify).
140//
141// This is mpfr_root_aux from root.c, MPFR 4.3.0, where the input is finite, nonzero, not a singular
142// value, |x| != 1, x is negative only for odd k, and rm is not `Exact`.
143fn root_u_aux(x: &Float, k: u64, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
144    let negative = x.is_sign_negative();
145    // Rounding modes are inverted for negative x, since t below approximates the magnitude of the
146    // root.
147    let rm_abs = if negative { -rm } else { rm };
148    let abs_x = x.abs();
149    let ex = i64::from(x.get_exponent().unwrap());
150    // Take some guard bits to prepare for the `exp_t` lost bits below. If 2^-k < |x| < 2^k, then
151    // |ln(x)| < k ln(2), thus taking log2(k) bits would be fine; in general |ln(x)| < |EXP(x)|
152    // ln(2), so take log2(|EXP(x)|) bits. (MPFR only guards for positive exponents; guarding for
153    // negative ones as well keeps the error bound below the working precision for tiny x at low
154    // target precisions.)
155    let mut working_prec = prec
156        + 10
157        + if ex == 0 {
158            0
159        } else {
160            ex.unsigned_abs().ceiling_log_base_2()
161        };
162    let kf = Float::exact_from(k);
163    let mut increment = Limb::WIDTH;
164    loop {
165        // t = ln|x| * (1 + theta) with |theta| <= 2^-working_prec
166        let mut t = abs_x.ln_prec_ref(working_prec).0;
167        // t = ln|x|/k * (1 + theta)^2; the total error is bounded by 1.5 * 2^(EXP(t) -
168        // working_prec)
169        t.div_prec_assign_ref(&kf, working_prec);
170        let exp_t = i64::from(t.get_exponent().unwrap());
171        // t = |x|^(1/k) * (1 + 2^(err - working_prec)); see root.c for the error analysis
172        t.exp_prec_assign(working_prec);
173        let err = match (exp_t + 2).sign() {
174            Greater => u64::exact_from(exp_t + 3),
175            Equal => 2,
176            Less => 1,
177        };
178        if working_prec > err
179            && float_can_round(
180                t.significand_ref().unwrap(),
181                working_prec - err,
182                prec,
183                rm_abs,
184            )
185        {
186            let (root, o) = Float::from_float_prec_round(t, prec, rm_abs);
187            return if negative {
188                (-root, o.reverse())
189            } else {
190                (root, o)
191            };
192        }
193        // If we fail to round correctly, check for an exact result or a midpoint result with
194        // `Nearest` (regarded as hard-to-round in all precisions in order to determine the ternary
195        // value).
196        let z = Float::from_float_prec_ref(&t, prec + u64::from(rm == Nearest)).0;
197        let (zk, o_pow) = z.pow_u_prec_ref(k, x.significant_bits());
198        if o_pow == Equal && zk == abs_x {
199            // z is the exact root, so round z directly.
200            let (root, o) = Float::from_float_prec_round(z, prec, rm_abs);
201            return if negative {
202                (-root, o.reverse())
203            } else {
204                (root, o)
205            };
206        }
207        working_prec += increment;
208        increment = working_prec >> 1;
209    }
210}
211
212// Computes the kth root of a nonzero `Rational` whose root is irrational, for k >= 2. The exponent
213// of x may be far outside the `Float` exponent range, so it is reduced first.
214fn root_u_rational_generic(x: &Rational, k: u64, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
215    let mut working_prec = prec + 10;
216    let mut increment = Limb::WIDTH;
217    let e = x.floor_log_base_2_abs();
218    if e.gt_abs(&0x3fff_0000) && k > 0x3fff_0000 {
219        // Both the exponent of x and k are huge. The exponent cannot be reduced to the
220        // representable range by shifting x by a multiple of k, so compute the root as root(x /
221        // 2^e) * 2^(e/k), where the second factor is 2 raised to a rational power. No overflow or
222        // underflow is possible: |e| is bounded by the bit size of x's numerator and denominator,
223        // so |e / k| < 2^30 - 1 by an enormous margin.
224        let xm = x >> e; // |xm| in [1, 2)
225        let p2_exp = Rational::from_signeds(e, i64::exact_from(k));
226        loop {
227            let mut root = Float::from_rational_prec_round_ref(&xm, working_prec, Floor)
228                .0
229                .root_u_prec(k, working_prec)
230                .0;
231            let p2 = Float::power_of_2_rational_prec_ref(&p2_exp, working_prec).0;
232            root.mul_prec_assign(p2, working_prec);
233            // Three roundings at working_prec plus the initial conversion error 2^(1 - wp) / k: the
234            // total relative error is below 2^(2 - wp), or 4 ulps.
235            if float_can_round(root.significand_ref().unwrap(), working_prec - 3, prec, rm) {
236                return Float::from_float_prec_round(root, prec, rm);
237            }
238            working_prec += increment;
239            increment = working_prec >> 1;
240        }
241    }
242    let ki = i64::exact_from(k);
243    let mut end_shift = e;
244    let x2;
245    let reduced_x: &Rational;
246    if end_shift.gt_abs(&0x3fff_0000) {
247        // Reduce the exponent of x to the representable range by shifting by a multiple of k, so
248        // that the root of the reduced value can be shifted back exactly (up to overflow or
249        // underflow, which the final `shl_prec_round_assign_helper` handles).
250        end_shift -= end_shift.rem_euclid(ki);
251        x2 = x >> end_shift;
252        reduced_x = &x2;
253    } else {
254        end_shift = 0;
255        reduced_x = x;
256    }
257    loop {
258        let root = Float::from_rational_prec_round_ref(reduced_x, working_prec, Floor)
259            .0
260            .root_u_prec(k, working_prec)
261            .0;
262        // The conversion error 2^(1 - wp) is contracted by the root to 2^(1 - wp) / k, and the root
263        // itself contributes at most 1/2 ulp, so the total relative error is below 2^(1 - wp), or 2
264        // ulps.
265        if float_can_round(root.significand_ref().unwrap(), working_prec - 2, prec, rm) {
266            let (mut root, mut o) = Float::from_float_prec_round(root, prec, rm);
267            if end_shift != 0 {
268                o = root.shl_prec_round_assign_helper(i128::from(end_shift / ki), prec, rm, o);
269            }
270            return (root, o);
271        }
272        working_prec += increment;
273        increment = working_prec >> 1;
274    }
275}
276
277impl Float {
278    /// Takes the $k$th root of a [`Float`], rounding the result to the specified precision and with
279    /// the specified rounding mode. The [`Float`] is taken by value. An [`Ordering`] is also
280    /// returned, indicating whether the rounded root is less than, equal to, or greater than the
281    /// exact root. Although `NaN`s are not comparable to any [`Float`], whenever this function
282    /// returns a `NaN` it also returns `Equal`.
283    ///
284    /// See [`RoundingMode`] for a description of the possible rounding modes.
285    ///
286    /// $$
287    /// f(x,k,p,m) = \sqrt\[k\]{x}+\varepsilon.
288    /// $$
289    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
290    ///   be 0.
291    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
292    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p+1}$.
293    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
294    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p}$.
295    ///
296    /// If the output has a precision, it is `prec`.
297    ///
298    /// Special cases:
299    /// - $f(\text{NaN},k,p,m)=\text{NaN}$
300    /// - $f(\infty,k,p,m)=\infty$
301    /// - $f(-\infty,k,p,m)=-\infty$ if $k$ is odd and `NaN` if $k$ is even
302    /// - $f(\pm0.0,k,p,m)=\pm0.0$ if $k$ is odd and $0.0$ if $k$ is even
303    /// - $f(x,0,p,m)=\text{NaN}$
304    /// - $f(x,1,p,m)=x$
305    /// - $f(x,k,p,m)=\text{NaN}$ if $x<0$ and $k$ is even
306    ///
307    /// The result never overflows or underflows: its exponent is close to the exponent of $x$
308    /// divided by $k$.
309    ///
310    /// If you know you'll be using `Nearest`, consider using [`Float::root_u_prec`] instead. If you
311    /// know that your target precision is the precision of the input, consider using
312    /// [`Float::root_u_round`] instead. If both of these things are true, consider using the
313    /// [`Root`] implementation instead.
314    ///
315    /// # Worst-case complexity
316    /// $T(n) = O(n^{3/2} \log n \log\log n)$
317    ///
318    /// $M(n) = O(n \log n)$
319    ///
320    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
321    ///
322    /// # Panics
323    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
324    /// with the given precision.
325    ///
326    /// # Examples
327    /// ```
328    /// use malachite_base::rounding_modes::RoundingMode::*;
329    /// use malachite_float::Float;
330    /// use std::cmp::Ordering::*;
331    ///
332    /// let (root, o) = Float::from(2.0).root_u_prec_round(3, 20, Floor);
333    /// assert_eq!(root.to_string(), "1.2599201");
334    /// assert_eq!(o, Less);
335    ///
336    /// let (root, o) = Float::from(2.0).root_u_prec_round(3, 20, Ceiling);
337    /// assert_eq!(root.to_string(), "1.2599220");
338    /// assert_eq!(o, Greater);
339    /// ```
340    #[inline]
341    pub fn root_u_prec_round(self, k: u64, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
342        self.root_u_prec_round_ref(k, prec, rm)
343    }
344
345    /// Takes the $k$th root of a [`Float`], rounding the result to the specified precision and with
346    /// the specified rounding mode. The [`Float`] is taken by reference. An [`Ordering`] is also
347    /// returned, indicating whether the rounded root is less than, equal to, or greater than the
348    /// exact root. Although `NaN`s are not comparable to any [`Float`], whenever this function
349    /// returns a `NaN` it also returns `Equal`.
350    ///
351    /// See [`RoundingMode`] for a description of the possible rounding modes.
352    ///
353    /// $$
354    /// f(x,k,p,m) = \sqrt\[k\]{x}+\varepsilon.
355    /// $$
356    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
357    ///   be 0.
358    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
359    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p+1}$.
360    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
361    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p}$.
362    ///
363    /// If the output has a precision, it is `prec`.
364    ///
365    /// Special cases:
366    /// - $f(\text{NaN},k,p,m)=\text{NaN}$
367    /// - $f(\infty,k,p,m)=\infty$
368    /// - $f(-\infty,k,p,m)=-\infty$ if $k$ is odd and `NaN` if $k$ is even
369    /// - $f(\pm0.0,k,p,m)=\pm0.0$ if $k$ is odd and $0.0$ if $k$ is even
370    /// - $f(x,0,p,m)=\text{NaN}$
371    /// - $f(x,1,p,m)=x$
372    /// - $f(x,k,p,m)=\text{NaN}$ if $x<0$ and $k$ is even
373    ///
374    /// The result never overflows or underflows: its exponent is close to the exponent of $x$
375    /// divided by $k$.
376    ///
377    /// If you know you'll be using `Nearest`, consider using [`Float::root_u_prec`] instead. If you
378    /// know that your target precision is the precision of the input, consider using
379    /// [`Float::root_u_round`] instead. If both of these things are true, consider using the
380    /// [`Root`] implementation instead.
381    ///
382    /// # Worst-case complexity
383    /// $T(n) = O(n^{3/2} \log n \log\log n)$
384    ///
385    /// $M(n) = O(n \log n)$
386    ///
387    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
388    ///
389    /// # Panics
390    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
391    /// with the given precision.
392    ///
393    /// # Examples
394    /// ```
395    /// use malachite_base::rounding_modes::RoundingMode::*;
396    /// use malachite_float::Float;
397    /// use std::cmp::Ordering::*;
398    ///
399    /// let (root, o) = Float::from(2.0).root_u_prec_round_ref(3, 20, Floor);
400    /// assert_eq!(root.to_string(), "1.2599201");
401    /// assert_eq!(o, Less);
402    ///
403    /// let (root, o) = Float::from(2.0).root_u_prec_round_ref(3, 20, Ceiling);
404    /// assert_eq!(root.to_string(), "1.2599220");
405    /// assert_eq!(o, Greater);
406    /// ```
407    pub fn root_u_prec_round_ref(&self, k: u64, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
408        assert_ne!(prec, 0);
409        if k == 0 {
410            // The 0th root of anything is NaN (IEEE 754-2008).
411            return (float_nan!(), Equal);
412        } else if k == 1 {
413            // x^(1/1) = x
414            return Self::from_float_prec_round_ref(self, prec, rm);
415        }
416        match self {
417            Self(NaN) => (float_nan!(), Equal),
418            Self(Infinity { sign }) => {
419                if *sign {
420                    // (+Infinity)^(1/k) = +Infinity
421                    (Self(Infinity { sign: true }), Equal)
422                } else if k.odd() {
423                    // (-Infinity)^(1/k) = -Infinity for odd k
424                    (Self(Infinity { sign: false }), Equal)
425                } else {
426                    // (-Infinity)^(1/k) = NaN for even k
427                    (float_nan!(), Equal)
428                }
429            }
430            // (+0.0)^(1/k) = +0.0; (-0.0)^(1/k) = +0.0 for even k and -0.0 for odd k
431            Self(Zero { sign }) => (
432                Self(Zero {
433                    sign: *sign || k.even(),
434                }),
435                Equal,
436            ),
437            _ => {
438                if self.is_sign_negative() && k.even() {
439                    // Negative x has no real kth root for even k.
440                    return (float_nan!(), Equal);
441                }
442                // |x| = 1: the root is x itself (if x is -1, then k is odd).
443                if *self == 1u32 || *self == -1i32 {
444                    return Self::from_float_prec_round_ref(self, prec, rm);
445                }
446                if k > HIGH_K_THRESHOLD {
447                    if rm == Exact {
448                        root_u_exact(self, k, prec)
449                    } else {
450                        root_u_aux(self, k, prec, rm)
451                    }
452                } else {
453                    root_u_integer(self, k, prec, rm)
454                }
455            }
456        }
457    }
458
459    /// Takes the $k$th root of a [`Float`], rounding the result to the nearest value of the
460    /// specified precision. The [`Float`] is taken by value. An [`Ordering`] is also returned,
461    /// indicating whether the rounded root is less than, equal to, or greater than the exact root.
462    /// Although `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN`
463    /// it also returns `Equal`.
464    ///
465    /// If the root is equidistant from two [`Float`]s with the specified precision, the [`Float`]
466    /// with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a description of
467    /// the `Nearest` rounding mode.
468    ///
469    /// $$
470    /// f(x,k,p) = \sqrt\[k\]{x}+\varepsilon.
471    /// $$
472    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
473    ///   be 0.
474    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, then $|\varepsilon| \leq 2^{\lfloor\log_2
475    ///   |\sqrt\[k\]{x}|\rfloor-p}$.
476    ///
477    /// If the output has a precision, it is `prec`.
478    ///
479    /// Special cases:
480    /// - $f(\text{NaN},k,p)=\text{NaN}$
481    /// - $f(\infty,k,p)=\infty$
482    /// - $f(-\infty,k,p)=-\infty$ if $k$ is odd and `NaN` if $k$ is even
483    /// - $f(\pm0.0,k,p)=\pm0.0$ if $k$ is odd and $0.0$ if $k$ is even
484    /// - $f(x,0,p,m)=\text{NaN}$
485    /// - $f(x,1,p,m)=x$
486    /// - $f(x,k,p)=\text{NaN}$ if $x<0$ and $k$ is even
487    ///
488    /// The result never overflows or underflows: its exponent is close to the exponent of $x$
489    /// divided by $k$.
490    ///
491    /// If you want to use a rounding mode other than `Nearest`, consider using
492    /// [`Float::root_u_prec_round`] instead.
493    ///
494    /// # Worst-case complexity
495    /// $T(n) = O(n^{3/2} \log n \log\log n)$
496    ///
497    /// $M(n) = O(n \log n)$
498    ///
499    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
500    ///
501    /// # Panics
502    /// Panics if `prec` is zero.
503    ///
504    /// # Examples
505    /// ```
506    /// use malachite_float::Float;
507    /// use std::cmp::Ordering::*;
508    ///
509    /// let (root, o) = Float::from(2.0).root_u_prec(3, 20);
510    /// assert_eq!(root.to_string(), "1.2599201");
511    /// assert_eq!(o, Less);
512    ///
513    /// let (root, o) = Float::from(2.0).root_u_prec(3, 53);
514    /// assert_eq!(root.to_string(), "1.2599210498948732");
515    /// assert_eq!(o, Greater);
516    /// ```
517    #[inline]
518    pub fn root_u_prec(self, k: u64, prec: u64) -> (Self, Ordering) {
519        self.root_u_prec_round(k, prec, Nearest)
520    }
521
522    /// Takes the $k$th root of a [`Float`], rounding the result to the nearest value of the
523    /// specified precision. The [`Float`] is taken by reference. An [`Ordering`] is also returned,
524    /// indicating whether the rounded root is less than, equal to, or greater than the exact root.
525    /// Although `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN`
526    /// it also returns `Equal`.
527    ///
528    /// If the root is equidistant from two [`Float`]s with the specified precision, the [`Float`]
529    /// with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a description of
530    /// the `Nearest` rounding mode.
531    ///
532    /// $$
533    /// f(x,k,p) = \sqrt\[k\]{x}+\varepsilon.
534    /// $$
535    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
536    ///   be 0.
537    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, then $|\varepsilon| \leq 2^{\lfloor\log_2
538    ///   |\sqrt\[k\]{x}|\rfloor-p}$.
539    ///
540    /// If the output has a precision, it is `prec`.
541    ///
542    /// Special cases:
543    /// - $f(\text{NaN},k,p)=\text{NaN}$
544    /// - $f(\infty,k,p)=\infty$
545    /// - $f(-\infty,k,p)=-\infty$ if $k$ is odd and `NaN` if $k$ is even
546    /// - $f(\pm0.0,k,p)=\pm0.0$ if $k$ is odd and $0.0$ if $k$ is even
547    /// - $f(x,0,p,m)=\text{NaN}$
548    /// - $f(x,1,p,m)=x$
549    /// - $f(x,k,p)=\text{NaN}$ if $x<0$ and $k$ is even
550    ///
551    /// The result never overflows or underflows: its exponent is close to the exponent of $x$
552    /// divided by $k$.
553    ///
554    /// If you want to use a rounding mode other than `Nearest`, consider using
555    /// [`Float::root_u_prec_round`] instead.
556    ///
557    /// # Worst-case complexity
558    /// $T(n) = O(n^{3/2} \log n \log\log n)$
559    ///
560    /// $M(n) = O(n \log n)$
561    ///
562    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
563    ///
564    /// # Panics
565    /// Panics if `prec` is zero.
566    ///
567    /// # Examples
568    /// ```
569    /// use malachite_float::Float;
570    /// use std::cmp::Ordering::*;
571    ///
572    /// let (root, o) = Float::from(2.0).root_u_prec_ref(3, 20);
573    /// assert_eq!(root.to_string(), "1.2599201");
574    /// assert_eq!(o, Less);
575    ///
576    /// let (root, o) = Float::from(2.0).root_u_prec_ref(3, 53);
577    /// assert_eq!(root.to_string(), "1.2599210498948732");
578    /// assert_eq!(o, Greater);
579    /// ```
580    #[inline]
581    pub fn root_u_prec_ref(&self, k: u64, prec: u64) -> (Self, Ordering) {
582        self.root_u_prec_round_ref(k, prec, Nearest)
583    }
584
585    /// Takes the $k$th root of a [`Float`], rounding the result with the specified rounding mode.
586    /// The precision of the output is the precision of the input. The [`Float`] is taken by value.
587    /// An [`Ordering`] is also returned, indicating whether the rounded root is less than, equal
588    /// to, or greater than the exact root. Although `NaN`s are not comparable to any [`Float`],
589    /// whenever this function returns a `NaN` it also returns `Equal`.
590    ///
591    /// See [`RoundingMode`] for a description of the possible rounding modes.
592    ///
593    /// $$
594    /// f(x,k,p,m) = \sqrt\[k\]{x}+\varepsilon.
595    /// $$
596    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
597    ///   be 0.
598    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
599    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p+1}$.
600    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
601    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p}$.
602    ///
603    /// If the output has a precision, it is the precision of the input.
604    ///
605    /// Special cases:
606    /// - $f(\text{NaN},k,p,m)=\text{NaN}$
607    /// - $f(\infty,k,p,m)=\infty$
608    /// - $f(-\infty,k,p,m)=-\infty$ if $k$ is odd and `NaN` if $k$ is even
609    /// - $f(\pm0.0,k,p,m)=\pm0.0$ if $k$ is odd and $0.0$ if $k$ is even
610    /// - $f(x,0,p,m)=\text{NaN}$
611    /// - $f(x,1,p,m)=x$
612    /// - $f(x,k,p,m)=\text{NaN}$ if $x<0$ and $k$ is even
613    ///
614    /// The result never overflows or underflows: its exponent is close to the exponent of $x$
615    /// divided by $k$.
616    ///
617    /// # Worst-case complexity
618    /// $T(n) = O(n^{3/2} \log n \log\log n)$
619    ///
620    /// $M(n) = O(n \log n)$
621    ///
622    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
623    ///
624    /// # Panics
625    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the input
626    /// precision.
627    ///
628    /// # Examples
629    /// ```
630    /// use malachite_base::rounding_modes::RoundingMode::*;
631    /// use malachite_float::Float;
632    /// use malachite_q::Rational;
633    /// use std::cmp::Ordering::*;
634    ///
635    /// let x = Float::from_rational_prec(Rational::from(2u32), 20).0;
636    /// let (root, o) = x.root_u_round(3, Floor);
637    /// assert_eq!(root.to_string(), "1.2599201");
638    /// assert_eq!(o, Less);
639    /// ```
640    #[inline]
641    pub fn root_u_round(self, k: u64, rm: RoundingMode) -> (Self, Ordering) {
642        let prec = self.significant_bits();
643        self.root_u_prec_round(k, prec, rm)
644    }
645
646    /// Takes the $k$th root of a [`Float`], rounding the result with the specified rounding mode.
647    /// The precision of the output is the precision of the input. The [`Float`] is taken by
648    /// reference. An [`Ordering`] is also returned, indicating whether the rounded root is less
649    /// than, equal to, or greater than the exact root. Although `NaN`s are not comparable to any
650    /// [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
651    ///
652    /// See [`RoundingMode`] for a description of the possible rounding modes.
653    ///
654    /// $$
655    /// f(x,k,p,m) = \sqrt\[k\]{x}+\varepsilon.
656    /// $$
657    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
658    ///   be 0.
659    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
660    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p+1}$.
661    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
662    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p}$.
663    ///
664    /// If the output has a precision, it is the precision of the input.
665    ///
666    /// Special cases:
667    /// - $f(\text{NaN},k,p,m)=\text{NaN}$
668    /// - $f(\infty,k,p,m)=\infty$
669    /// - $f(-\infty,k,p,m)=-\infty$ if $k$ is odd and `NaN` if $k$ is even
670    /// - $f(\pm0.0,k,p,m)=\pm0.0$ if $k$ is odd and $0.0$ if $k$ is even
671    /// - $f(x,0,p,m)=\text{NaN}$
672    /// - $f(x,1,p,m)=x$
673    /// - $f(x,k,p,m)=\text{NaN}$ if $x<0$ and $k$ is even
674    ///
675    /// The result never overflows or underflows: its exponent is close to the exponent of $x$
676    /// divided by $k$.
677    ///
678    /// # Worst-case complexity
679    /// $T(n) = O(n^{3/2} \log n \log\log n)$
680    ///
681    /// $M(n) = O(n \log n)$
682    ///
683    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
684    ///
685    /// # Panics
686    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the input
687    /// precision.
688    ///
689    /// # Examples
690    /// ```
691    /// use malachite_base::rounding_modes::RoundingMode::*;
692    /// use malachite_float::Float;
693    /// use malachite_q::Rational;
694    /// use std::cmp::Ordering::*;
695    ///
696    /// let x = Float::from_rational_prec(Rational::from(2u32), 20).0;
697    /// let (root, o) = x.root_u_round_ref(3, Floor);
698    /// assert_eq!(root.to_string(), "1.2599201");
699    /// assert_eq!(o, Less);
700    /// ```
701    #[inline]
702    pub fn root_u_round_ref(&self, k: u64, rm: RoundingMode) -> (Self, Ordering) {
703        self.root_u_prec_round_ref(k, self.significant_bits(), rm)
704    }
705
706    /// Takes the $k$th root of a [`Float`] in place, rounding the result to the specified precision
707    /// and with the specified rounding mode. An [`Ordering`] is returned, indicating whether the
708    /// rounded root is less than, equal to, or greater than the exact root.
709    ///
710    /// See [`RoundingMode`] for a description of the possible rounding modes.
711    ///
712    /// $$
713    /// x \gets \sqrt\[k\]{x}+\varepsilon.
714    /// $$
715    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
716    ///   be 0.
717    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
718    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p+1}$.
719    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
720    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p}$.
721    ///
722    /// Special cases: see [`Float::root_u_prec_round`].
723    ///
724    /// # Worst-case complexity
725    /// $T(n) = O(n^{3/2} \log n \log\log n)$
726    ///
727    /// $M(n) = O(n \log n)$
728    ///
729    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
730    ///
731    /// # Panics
732    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
733    /// with the given precision.
734    ///
735    /// # Examples
736    /// ```
737    /// use malachite_base::rounding_modes::RoundingMode::*;
738    /// use malachite_float::Float;
739    /// use std::cmp::Ordering::*;
740    ///
741    /// let mut x = Float::from(2.0);
742    /// assert_eq!(x.root_u_prec_round_assign(3, 20, Floor), Less);
743    /// assert_eq!(x.to_string(), "1.2599201");
744    /// ```
745    #[inline]
746    pub fn root_u_prec_round_assign(&mut self, k: u64, prec: u64, rm: RoundingMode) -> Ordering {
747        let (root, o) = core::mem::take(self).root_u_prec_round(k, prec, rm);
748        *self = root;
749        o
750    }
751
752    /// Takes the $k$th root of a [`Float`] in place, rounding the result to the nearest value of
753    /// the specified precision. An [`Ordering`] is returned, indicating whether the rounded root is
754    /// less than, equal to, or greater than the exact root.
755    ///
756    /// Special cases: see [`Float::root_u_prec`].
757    ///
758    /// # Worst-case complexity
759    /// $T(n) = O(n^{3/2} \log n \log\log n)$
760    ///
761    /// $M(n) = O(n \log n)$
762    ///
763    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
764    ///
765    /// # Panics
766    /// Panics if `prec` is zero.
767    ///
768    /// # Examples
769    /// ```
770    /// use malachite_float::Float;
771    /// use std::cmp::Ordering::*;
772    ///
773    /// let mut x = Float::from(2.0);
774    /// assert_eq!(x.root_u_prec_assign(3, 20), Less);
775    /// assert_eq!(x.to_string(), "1.2599201");
776    /// ```
777    #[inline]
778    pub fn root_u_prec_assign(&mut self, k: u64, prec: u64) -> Ordering {
779        self.root_u_prec_round_assign(k, prec, Nearest)
780    }
781
782    /// Takes the $k$th root of a [`Float`] in place, rounding the result with the specified
783    /// rounding mode. The precision is retained. An [`Ordering`] is returned, indicating whether
784    /// the rounded root is less than, equal to, or greater than the exact root.
785    ///
786    /// Special cases: see [`Float::root_u_round`].
787    ///
788    /// # Worst-case complexity
789    /// $T(n) = O(n^{3/2} \log n \log\log n)$
790    ///
791    /// $M(n) = O(n \log n)$
792    ///
793    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
794    ///
795    /// # Panics
796    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the input
797    /// precision.
798    ///
799    /// # Examples
800    /// ```
801    /// use malachite_base::rounding_modes::RoundingMode::*;
802    /// use malachite_float::Float;
803    /// use malachite_q::Rational;
804    /// use std::cmp::Ordering::*;
805    ///
806    /// let mut x = Float::from_rational_prec(Rational::from(2u32), 20).0;
807    /// assert_eq!(x.root_u_round_assign(3, Nearest), Less);
808    /// assert_eq!(x.to_string(), "1.2599201");
809    /// ```
810    #[inline]
811    pub fn root_u_round_assign(&mut self, k: u64, rm: RoundingMode) -> Ordering {
812        let prec = self.significant_bits();
813        self.root_u_prec_round_assign(k, prec, rm)
814    }
815
816    /// Takes the $k$th root of a [`Float`], where $k$ may be negative, rounding the result to the
817    /// specified precision and with the specified rounding mode. The [`Float`] is taken by value.
818    /// An [`Ordering`] is also returned, indicating whether the rounded root is less than, equal
819    /// to, or greater than the exact root. Although `NaN`s are not comparable to any [`Float`],
820    /// whenever this function returns a `NaN` it also returns `Equal`.
821    ///
822    /// See [`RoundingMode`] for a description of the possible rounding modes.
823    ///
824    /// $$
825    /// f(x,k,p,m) = \sqrt\[k\]{x}+\varepsilon.
826    /// $$
827    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
828    ///   be 0.
829    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
830    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p+1}$.
831    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
832    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p}$.
833    ///
834    /// If the output has a precision, it is `prec`.
835    ///
836    /// Special cases for $k<0$ (for $k\geq 0$ the cases are those of the unsigned version):
837    /// - $f(\text{NaN},k,p,m)=\text{NaN}$
838    /// - $f(\infty,k,p,m)=0.0$
839    /// - $f(-\infty,k,p,m)=-0.0$ if $k$ is odd and `NaN` if $k$ is even
840    /// - $f(\pm0.0,k,p,m)=\pm\infty$ if $k$ is odd and $\infty$ if $k$ is even
841    /// - $f(x,k,p,m)=\text{NaN}$ if $x<0$ and $k$ is even
842    ///
843    /// Overflow and underflow are possible only for $k=-1$ (the reciprocal); for other $k$ the
844    /// result's exponent is close to the exponent of $x$ divided by $k$, always within range.
845    ///
846    /// If you know you'll be using `Nearest`, consider using [`Float::root_s_prec`] instead. If you
847    /// know that your target precision is the precision of the input, consider using
848    /// [`Float::root_s_round`] instead. If both of these things are true, consider using the
849    /// [`Root`] implementation instead.
850    ///
851    /// # Worst-case complexity
852    /// $T(n) = O(n^{3/2} \log n \log\log n)$
853    ///
854    /// $M(n) = O(n \log n)$
855    ///
856    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
857    ///
858    /// # Panics
859    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
860    /// with the given precision.
861    ///
862    /// # Examples
863    /// ```
864    /// use malachite_base::rounding_modes::RoundingMode::*;
865    /// use malachite_float::Float;
866    /// use std::cmp::Ordering::*;
867    ///
868    /// let (root, o) = Float::from(2.0).root_s_prec_round(-3, 20, Floor);
869    /// assert_eq!(root.to_string(), "0.79370022");
870    /// assert_eq!(o, Less);
871    ///
872    /// let (root, o) = Float::from(2.0).root_s_prec_round(-3, 20, Ceiling);
873    /// assert_eq!(root.to_string(), "0.79370117");
874    /// assert_eq!(o, Greater);
875    /// ```
876    #[inline]
877    pub fn root_s_prec_round(self, k: i64, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
878        self.root_s_prec_round_ref(k, prec, rm)
879    }
880
881    /// Takes the $k$th root of a [`Float`], where $k$ may be negative, rounding the result to the
882    /// specified precision and with the specified rounding mode. The [`Float`] is taken by
883    /// reference. An [`Ordering`] is also returned, indicating whether the rounded root is less
884    /// than, equal to, or greater than the exact root. Although `NaN`s are not comparable to any
885    /// [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
886    ///
887    /// See [`RoundingMode`] for a description of the possible rounding modes.
888    ///
889    /// $$
890    /// f(x,k,p,m) = \sqrt\[k\]{x}+\varepsilon.
891    /// $$
892    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
893    ///   be 0.
894    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
895    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p+1}$.
896    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
897    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p}$.
898    ///
899    /// If the output has a precision, it is `prec`.
900    ///
901    /// Special cases for $k<0$ (for $k\geq 0$ the cases are those of the unsigned version):
902    /// - $f(\text{NaN},k,p,m)=\text{NaN}$
903    /// - $f(\infty,k,p,m)=0.0$
904    /// - $f(-\infty,k,p,m)=-0.0$ if $k$ is odd and `NaN` if $k$ is even
905    /// - $f(\pm0.0,k,p,m)=\pm\infty$ if $k$ is odd and $\infty$ if $k$ is even
906    /// - $f(x,k,p,m)=\text{NaN}$ if $x<0$ and $k$ is even
907    ///
908    /// Overflow and underflow are possible only for $k=-1$ (the reciprocal); for other $k$ the
909    /// result's exponent is close to the exponent of $x$ divided by $k$, always within range.
910    ///
911    /// If you know you'll be using `Nearest`, consider using [`Float::root_s_prec`] instead. If you
912    /// know that your target precision is the precision of the input, consider using
913    /// [`Float::root_s_round`] instead. If both of these things are true, consider using the
914    /// [`Root`] implementation instead.
915    ///
916    /// # Worst-case complexity
917    /// $T(n) = O(n^{3/2} \log n \log\log n)$
918    ///
919    /// $M(n) = O(n \log n)$
920    ///
921    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
922    ///
923    /// # Panics
924    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
925    /// with the given precision.
926    ///
927    /// # Examples
928    /// ```
929    /// use malachite_base::rounding_modes::RoundingMode::*;
930    /// use malachite_float::Float;
931    /// use std::cmp::Ordering::*;
932    ///
933    /// let (root, o) = Float::from(2.0).root_s_prec_round_ref(-3, 20, Floor);
934    /// assert_eq!(root.to_string(), "0.79370022");
935    /// assert_eq!(o, Less);
936    ///
937    /// let (root, o) = Float::from(2.0).root_s_prec_round_ref(-3, 20, Ceiling);
938    /// assert_eq!(root.to_string(), "0.79370117");
939    /// assert_eq!(o, Greater);
940    /// ```
941    pub fn root_s_prec_round_ref(&self, k: i64, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
942        if k >= 0 {
943            return self.root_u_prec_round_ref(k.unsigned_abs(), prec, rm);
944        }
945        assert_ne!(prec, 0);
946        // Singular values for k < 0
947        match self {
948            Self(NaN) => (float_nan!(), Equal),
949            Self(Infinity { sign }) => {
950                if *sign || k.odd() {
951                    // (+Infinity)^(1/k) = +0.0; (-Infinity)^(1/k) = -0.0 for odd k
952                    (Self(Zero { sign: *sign }), Equal)
953                } else {
954                    // (-Infinity)^(1/k) = NaN for even k
955                    (float_nan!(), Equal)
956                }
957            }
958            Self(Zero { sign }) => {
959                // (+0.0)^(1/k) = +Infinity; (-0.0)^(1/k) = +Infinity for even k and -Infinity for
960                // odd k
961                (
962                    Self(Infinity {
963                        sign: *sign || k.even(),
964                    }),
965                    Equal,
966                )
967            }
968            _ => {
969                if self.is_sign_negative() && k.even() {
970                    // Negative x has no real kth root for even k.
971                    return (float_nan!(), Equal);
972                }
973                // |x| = 1: the root is x itself (if x is -1, then k is odd).
974                if *self == 1u32 || *self == -1i32 {
975                    return Self::from_float_prec_round_ref(self, prec, rm);
976                }
977                // k = -1 is x^-1 and k = -2 is 1/sqrt(x); both have specialized implementations
978                // that also handle the overflow and underflow that are possible when k = -1.
979                if k == -1 {
980                    return self.reciprocal_prec_round_ref(prec, rm);
981                } else if k == -2 {
982                    return self.reciprocal_sqrt_prec_round_ref(prec, rm);
983                }
984                let ku = k.unsigned_abs();
985                if rm == Exact {
986                    // The root is exactly representable iff |x| is 2 raised to a multiple of k.
987                    let e = i64::from(self.get_exponent().unwrap()) - 1;
988                    if self.significand_ref().unwrap().is_power_of_2() && e.divisible_by(k) {
989                        let (root, o) =
990                            Self::from_float_prec_round_ref(&(Self::ONE << (e / k)), prec, Exact);
991                        debug_assert_eq!(o, Equal);
992                        return if self.is_sign_negative() {
993                            (-root, Equal)
994                        } else {
995                            (root, Equal)
996                        };
997                    }
998                    panic!("Inexact root");
999                }
1000                // General case: compute the |k|th root, then invert. The root is computed before
1001                // the division so that overflow and underflow are impossible, and midpoints are
1002                // impossible as well. An exact case implies that |x| is a power of 2; it is
1003                // detected after `float_can_round`. The root is exactly representable iff |x| is 2
1004                // raised to a multiple of k.
1005                let exact_representable = self.significand_ref().unwrap().is_power_of_2()
1006                    && (i64::from(self.get_exponent().unwrap()) - 1).divisible_by(k);
1007                let mut working_prec = prec + 10;
1008                let mut increment = Limb::WIDTH;
1009                loop {
1010                    // (MPFR uses faithful rounding here to avoid the potentially costly detection
1011                    // of exact cases in the underlying root; `Nearest` is used instead, which only
1012                    // improves the error bound.)
1013                    let mut t = self.root_u_prec_ref(ku, working_prec).0;
1014                    let o = t.reciprocal_prec_round_assign(working_prec, rm);
1015                    // The final error is bounded by 5 ulps (see algorithms.tex, "Generic error of
1016                    // inverse"), which is <= 2^3 ulps.
1017                    //
1018                    // The exact-case escape must verify divisibility of the exponent, not just that
1019                    // |x| is a power of 2 (MPFR's condition): otherwise a root that merely rounds
1020                    // to a power of 2 at the working precision (for example 0.5^(1/50000) ~ 1 at
1021                    // low precisions), followed by an exact reciprocal, is mistaken for an exact
1022                    // result.
1023                    if float_can_round(t.significand_ref().unwrap(), working_prec - 3, prec, rm)
1024                        || (o == Equal && exact_representable)
1025                    {
1026                        return Self::from_float_prec_round(t, prec, rm);
1027                    }
1028                    working_prec += increment;
1029                    increment = working_prec >> 1;
1030                }
1031            }
1032        }
1033    }
1034
1035    /// Takes the $k$th root of a [`Float`], where $k$ may be negative, rounding the result to the
1036    /// nearest value of the specified precision. The [`Float`] is taken by value. An [`Ordering`]
1037    /// is also returned, indicating whether the rounded root is less than, equal to, or greater
1038    /// than the exact root. Although `NaN`s are not comparable to any [`Float`], whenever this
1039    /// function returns a `NaN` it also returns `Equal`.
1040    ///
1041    /// If the root is equidistant from two [`Float`]s with the specified precision, the [`Float`]
1042    /// with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a description of
1043    /// the `Nearest` rounding mode.
1044    ///
1045    /// $$
1046    /// f(x,k,p) = \sqrt\[k\]{x}+\varepsilon.
1047    /// $$
1048    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
1049    ///   be 0.
1050    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, then $|\varepsilon| \leq 2^{\lfloor\log_2
1051    ///   |\sqrt\[k\]{x}|\rfloor-p}$.
1052    ///
1053    /// If the output has a precision, it is `prec`.
1054    ///
1055    /// Special cases for $k<0$ (for $k\geq 0$ the cases are those of the unsigned version):
1056    /// - $f(\text{NaN},k,p)=\text{NaN}$
1057    /// - $f(\infty,k,p)=0.0$
1058    /// - $f(-\infty,k,p)=-0.0$ if $k$ is odd and `NaN` if $k$ is even
1059    /// - $f(\pm0.0,k,p)=\pm\infty$ if $k$ is odd and $\infty$ if $k$ is even
1060    /// - $f(x,k,p)=\text{NaN}$ if $x<0$ and $k$ is even
1061    ///
1062    /// Overflow and underflow are possible only for $k=-1$ (the reciprocal); for other $k$ the
1063    /// result's exponent is close to the exponent of $x$ divided by $k$, always within range.
1064    ///
1065    /// If you want to use a rounding mode other than `Nearest`, consider using
1066    /// [`Float::root_s_prec_round`] instead.
1067    ///
1068    /// # Worst-case complexity
1069    /// $T(n) = O(n^{3/2} \log n \log\log n)$
1070    ///
1071    /// $M(n) = O(n \log n)$
1072    ///
1073    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
1074    ///
1075    /// # Panics
1076    /// Panics if `prec` is zero.
1077    ///
1078    /// # Examples
1079    /// ```
1080    /// use malachite_float::Float;
1081    /// use std::cmp::Ordering::*;
1082    ///
1083    /// let (root, o) = Float::from(2.0).root_s_prec(-3, 53);
1084    /// assert_eq!(root.to_string(), "0.79370052598409979");
1085    /// assert_eq!(o, Greater);
1086    /// ```
1087    #[inline]
1088    pub fn root_s_prec(self, k: i64, prec: u64) -> (Self, Ordering) {
1089        self.root_s_prec_round(k, prec, Nearest)
1090    }
1091
1092    /// Takes the $k$th root of a [`Float`], where $k$ may be negative, rounding the result to the
1093    /// nearest value of the specified precision. The [`Float`] is taken by reference. An
1094    /// [`Ordering`] is also returned, indicating whether the rounded root is less than, equal to,
1095    /// or greater than the exact root. Although `NaN`s are not comparable to any [`Float`],
1096    /// whenever this function returns a `NaN` it also returns `Equal`.
1097    ///
1098    /// If the root is equidistant from two [`Float`]s with the specified precision, the [`Float`]
1099    /// with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a description of
1100    /// the `Nearest` rounding mode.
1101    ///
1102    /// $$
1103    /// f(x,k,p) = \sqrt\[k\]{x}+\varepsilon.
1104    /// $$
1105    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
1106    ///   be 0.
1107    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, then $|\varepsilon| \leq 2^{\lfloor\log_2
1108    ///   |\sqrt\[k\]{x}|\rfloor-p}$.
1109    ///
1110    /// If the output has a precision, it is `prec`.
1111    ///
1112    /// Special cases for $k<0$ (for $k\geq 0$ the cases are those of the unsigned version):
1113    /// - $f(\text{NaN},k,p)=\text{NaN}$
1114    /// - $f(\infty,k,p)=0.0$
1115    /// - $f(-\infty,k,p)=-0.0$ if $k$ is odd and `NaN` if $k$ is even
1116    /// - $f(\pm0.0,k,p)=\pm\infty$ if $k$ is odd and $\infty$ if $k$ is even
1117    /// - $f(x,k,p)=\text{NaN}$ if $x<0$ and $k$ is even
1118    ///
1119    /// Overflow and underflow are possible only for $k=-1$ (the reciprocal); for other $k$ the
1120    /// result's exponent is close to the exponent of $x$ divided by $k$, always within range.
1121    ///
1122    /// If you want to use a rounding mode other than `Nearest`, consider using
1123    /// [`Float::root_s_prec_round`] instead.
1124    ///
1125    /// # Worst-case complexity
1126    /// $T(n) = O(n^{3/2} \log n \log\log n)$
1127    ///
1128    /// $M(n) = O(n \log n)$
1129    ///
1130    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
1131    ///
1132    /// # Panics
1133    /// Panics if `prec` is zero.
1134    ///
1135    /// # Examples
1136    /// ```
1137    /// use malachite_float::Float;
1138    /// use std::cmp::Ordering::*;
1139    ///
1140    /// let (root, o) = Float::from(2.0).root_s_prec_ref(-3, 53);
1141    /// assert_eq!(root.to_string(), "0.79370052598409979");
1142    /// assert_eq!(o, Greater);
1143    /// ```
1144    #[inline]
1145    pub fn root_s_prec_ref(&self, k: i64, prec: u64) -> (Self, Ordering) {
1146        self.root_s_prec_round_ref(k, prec, Nearest)
1147    }
1148
1149    /// Takes the $k$th root of a [`Float`], where $k$ may be negative, rounding the result with the
1150    /// specified rounding mode. The precision of the output is the precision of the input. The
1151    /// [`Float`] is taken by value. An [`Ordering`] is also returned, indicating whether the
1152    /// rounded root is less than, equal to, or greater than the exact root. Although `NaN`s are not
1153    /// comparable to any [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
1154    ///
1155    /// See [`RoundingMode`] for a description of the possible rounding modes.
1156    ///
1157    /// $$
1158    /// f(x,k,p,m) = \sqrt\[k\]{x}+\varepsilon.
1159    /// $$
1160    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
1161    ///   be 0.
1162    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
1163    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p+1}$.
1164    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
1165    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p}$.
1166    ///
1167    /// If the output has a precision, it is the precision of the input.
1168    ///
1169    /// Special cases for $k<0$ (for $k\geq 0$ the cases are those of the unsigned version):
1170    /// - $f(\text{NaN},k,p,m)=\text{NaN}$
1171    /// - $f(\infty,k,p,m)=0.0$
1172    /// - $f(-\infty,k,p,m)=-0.0$ if $k$ is odd and `NaN` if $k$ is even
1173    /// - $f(\pm0.0,k,p,m)=\pm\infty$ if $k$ is odd and $\infty$ if $k$ is even
1174    /// - $f(x,k,p,m)=\text{NaN}$ if $x<0$ and $k$ is even
1175    ///
1176    /// Overflow and underflow are possible only for $k=-1$ (the reciprocal); for other $k$ the
1177    /// result's exponent is close to the exponent of $x$ divided by $k$, always within range.
1178    ///
1179    /// # Worst-case complexity
1180    /// $T(n) = O(n^{3/2} \log n \log\log n)$
1181    ///
1182    /// $M(n) = O(n \log n)$
1183    ///
1184    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
1185    ///
1186    /// # Panics
1187    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the input
1188    /// precision.
1189    ///
1190    /// # Examples
1191    /// ```
1192    /// use malachite_base::rounding_modes::RoundingMode::*;
1193    /// use malachite_float::Float;
1194    /// use malachite_q::Rational;
1195    /// use std::cmp::Ordering::*;
1196    ///
1197    /// let x = Float::from_rational_prec(Rational::from(2u32), 20).0;
1198    /// let (root, o) = x.root_s_round(-3, Ceiling);
1199    /// assert_eq!(root.to_string(), "0.79370117");
1200    /// assert_eq!(o, Greater);
1201    /// ```
1202    #[inline]
1203    pub fn root_s_round(self, k: i64, rm: RoundingMode) -> (Self, Ordering) {
1204        let prec = self.significant_bits();
1205        self.root_s_prec_round(k, prec, rm)
1206    }
1207
1208    /// Takes the $k$th root of a [`Float`], where $k$ may be negative, rounding the result with the
1209    /// specified rounding mode. The precision of the output is the precision of the input. The
1210    /// [`Float`] is taken by reference. An [`Ordering`] is also returned, indicating whether the
1211    /// rounded root is less than, equal to, or greater than the exact root. Although `NaN`s are not
1212    /// comparable to any [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
1213    ///
1214    /// See [`RoundingMode`] for a description of the possible rounding modes.
1215    ///
1216    /// $$
1217    /// f(x,k,p,m) = \sqrt\[k\]{x}+\varepsilon.
1218    /// $$
1219    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
1220    ///   be 0.
1221    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
1222    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p+1}$.
1223    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
1224    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p}$.
1225    ///
1226    /// If the output has a precision, it is the precision of the input.
1227    ///
1228    /// Special cases for $k<0$ (for $k\geq 0$ the cases are those of the unsigned version):
1229    /// - $f(\text{NaN},k,p,m)=\text{NaN}$
1230    /// - $f(\infty,k,p,m)=0.0$
1231    /// - $f(-\infty,k,p,m)=-0.0$ if $k$ is odd and `NaN` if $k$ is even
1232    /// - $f(\pm0.0,k,p,m)=\pm\infty$ if $k$ is odd and $\infty$ if $k$ is even
1233    /// - $f(x,k,p,m)=\text{NaN}$ if $x<0$ and $k$ is even
1234    ///
1235    /// Overflow and underflow are possible only for $k=-1$ (the reciprocal); for other $k$ the
1236    /// result's exponent is close to the exponent of $x$ divided by $k$, always within range.
1237    ///
1238    /// # Worst-case complexity
1239    /// $T(n) = O(n^{3/2} \log n \log\log n)$
1240    ///
1241    /// $M(n) = O(n \log n)$
1242    ///
1243    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
1244    ///
1245    /// # Panics
1246    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the input
1247    /// precision.
1248    ///
1249    /// # Examples
1250    /// ```
1251    /// use malachite_base::rounding_modes::RoundingMode::*;
1252    /// use malachite_float::Float;
1253    /// use malachite_q::Rational;
1254    /// use std::cmp::Ordering::*;
1255    ///
1256    /// let x = Float::from_rational_prec(Rational::from(2u32), 20).0;
1257    /// let (root, o) = x.root_s_round_ref(-3, Ceiling);
1258    /// assert_eq!(root.to_string(), "0.79370117");
1259    /// assert_eq!(o, Greater);
1260    /// ```
1261    #[inline]
1262    pub fn root_s_round_ref(&self, k: i64, rm: RoundingMode) -> (Self, Ordering) {
1263        self.root_s_prec_round_ref(k, self.significant_bits(), rm)
1264    }
1265
1266    /// Takes the $k$th root of a [`Float`] in place, where $k$ may be negative, rounding the result
1267    /// to the specified precision and with the specified rounding mode. An [`Ordering`] is
1268    /// returned, indicating whether the rounded root is less than, equal to, or greater than the
1269    /// exact root.
1270    ///
1271    /// Special cases: see [`Float::root_s_prec_round`].
1272    ///
1273    /// # Worst-case complexity
1274    /// $T(n) = O(n^{3/2} \log n \log\log n)$
1275    ///
1276    /// $M(n) = O(n \log n)$
1277    ///
1278    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
1279    ///
1280    /// # Panics
1281    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
1282    /// with the given precision.
1283    ///
1284    /// # Examples
1285    /// ```
1286    /// use malachite_base::rounding_modes::RoundingMode::*;
1287    /// use malachite_float::Float;
1288    /// use std::cmp::Ordering::*;
1289    ///
1290    /// let mut x = Float::from(2.0);
1291    /// assert_eq!(x.root_s_prec_round_assign(-3, 20, Floor), Less);
1292    /// assert_eq!(x.to_string(), "0.79370022");
1293    /// ```
1294    #[inline]
1295    pub fn root_s_prec_round_assign(&mut self, k: i64, prec: u64, rm: RoundingMode) -> Ordering {
1296        let (root, o) = core::mem::take(self).root_s_prec_round(k, prec, rm);
1297        *self = root;
1298        o
1299    }
1300
1301    /// Takes the $k$th root of a [`Float`] in place, where $k$ may be negative, rounding the result
1302    /// to the nearest value of the specified precision. An [`Ordering`] is returned, indicating
1303    /// whether the rounded root is less than, equal to, or greater than the exact root.
1304    ///
1305    /// Special cases: see [`Float::root_s_prec`].
1306    ///
1307    /// # Worst-case complexity
1308    /// $T(n) = O(n^{3/2} \log n \log\log n)$
1309    ///
1310    /// $M(n) = O(n \log n)$
1311    ///
1312    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
1313    ///
1314    /// # Panics
1315    /// Panics if `prec` is zero.
1316    ///
1317    /// # Examples
1318    /// ```
1319    /// use malachite_float::Float;
1320    /// use std::cmp::Ordering::*;
1321    ///
1322    /// let mut x = Float::from(2.0);
1323    /// assert_eq!(x.root_s_prec_assign(-3, 20), Less);
1324    /// assert_eq!(x.to_string(), "0.79370022");
1325    /// ```
1326    #[inline]
1327    pub fn root_s_prec_assign(&mut self, k: i64, prec: u64) -> Ordering {
1328        self.root_s_prec_round_assign(k, prec, Nearest)
1329    }
1330
1331    /// Takes the $k$th root of a [`Float`] in place, where $k$ may be negative, rounding the result
1332    /// with the specified rounding mode. The precision is retained. An [`Ordering`] is returned,
1333    /// indicating whether the rounded root is less than, equal to, or greater than the exact root.
1334    ///
1335    /// Special cases: see [`Float::root_s_round`].
1336    ///
1337    /// # Worst-case complexity
1338    /// $T(n) = O(n^{3/2} \log n \log\log n)$
1339    ///
1340    /// $M(n) = O(n \log n)$
1341    ///
1342    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
1343    ///
1344    /// # Panics
1345    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the input
1346    /// precision.
1347    ///
1348    /// # Examples
1349    /// ```
1350    /// use malachite_base::rounding_modes::RoundingMode::*;
1351    /// use malachite_float::Float;
1352    /// use malachite_q::Rational;
1353    /// use std::cmp::Ordering::*;
1354    ///
1355    /// let mut x = Float::from_rational_prec(Rational::from(2u32), 20).0;
1356    /// assert_eq!(x.root_s_round_assign(-3, Nearest), Less);
1357    /// assert_eq!(x.to_string(), "0.79370022");
1358    /// ```
1359    #[inline]
1360    pub fn root_s_round_assign(&mut self, k: i64, rm: RoundingMode) -> Ordering {
1361        let prec = self.significant_bits();
1362        self.root_s_prec_round_assign(k, prec, rm)
1363    }
1364
1365    /// Takes the $k$th root of a [`Rational`], rounding the result to the specified precision and
1366    /// with the specified rounding mode and returning the result as a [`Float`]. The [`Rational`]
1367    /// is taken by value. An [`Ordering`] is also returned, indicating whether the rounded root is
1368    /// less than, equal to, or greater than the exact root. Although `NaN`s are not comparable to
1369    /// any [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
1370    ///
1371    /// See [`RoundingMode`] for a description of the possible rounding modes.
1372    ///
1373    /// $$
1374    /// f(x,k,p,m) = \sqrt\[k\]{x}+\varepsilon.
1375    /// $$
1376    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
1377    ///   be 0.
1378    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
1379    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p+1}$.
1380    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
1381    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p}$.
1382    ///
1383    /// If the output has a precision, it is `prec`.
1384    ///
1385    /// Special cases:
1386    /// - $f(0,k,p,m)=0.0$
1387    /// - $f(x,0,p,m)=\text{NaN}$
1388    /// - $f(x,1,p,m)=x$
1389    /// - $f(x,k,p,m)=\text{NaN}$ if $x<0$ and $k$ is even
1390    ///
1391    /// Overflow and underflow are possible when the exponent of $x$ exceeds $k$ times the maximum
1392    /// [`Float`] exponent in absolute value.
1393    ///
1394    /// If you know you'll be using `Nearest`, consider using [`Float::root_u_rational_prec`]
1395    /// instead.
1396    ///
1397    /// # Worst-case complexity
1398    /// $T(n) = O(n^{3/2} \log n \log\log n)$
1399    ///
1400    /// $M(n) = O(n \log n)$
1401    ///
1402    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
1403    ///
1404    /// # Panics
1405    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
1406    /// with the given precision.
1407    ///
1408    /// # Examples
1409    /// ```
1410    /// use malachite_base::rounding_modes::RoundingMode::*;
1411    /// use malachite_float::Float;
1412    /// use malachite_q::Rational;
1413    /// use std::cmp::Ordering::*;
1414    ///
1415    /// let (root, o) =
1416    ///     Float::root_u_rational_prec_round(Rational::from_signeds(3, 5), 3, 20, Floor);
1417    /// assert_eq!(root.to_string(), "0.84343243");
1418    /// assert_eq!(o, Less);
1419    ///
1420    /// let (root, o) =
1421    ///     Float::root_u_rational_prec_round(Rational::from_signeds(3, 5), 3, 20, Ceiling);
1422    /// assert_eq!(root.to_string(), "0.84343338");
1423    /// assert_eq!(o, Greater);
1424    /// ```
1425    #[allow(clippy::needless_pass_by_value)]
1426    #[inline]
1427    pub fn root_u_rational_prec_round(
1428        x: Rational,
1429        k: u64,
1430        prec: u64,
1431        rm: RoundingMode,
1432    ) -> (Self, Ordering) {
1433        Self::root_u_rational_prec_round_ref(&x, k, prec, rm)
1434    }
1435
1436    /// Takes the $k$th root of a [`Rational`], rounding the result to the specified precision and
1437    /// with the specified rounding mode and returning the result as a [`Float`]. The [`Rational`]
1438    /// is taken by reference. An [`Ordering`] is also returned, indicating whether the rounded root
1439    /// is less than, equal to, or greater than the exact root. Although `NaN`s are not comparable
1440    /// to any [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
1441    ///
1442    /// See [`RoundingMode`] for a description of the possible rounding modes.
1443    ///
1444    /// $$
1445    /// f(x,k,p,m) = \sqrt\[k\]{x}+\varepsilon.
1446    /// $$
1447    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
1448    ///   be 0.
1449    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
1450    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p+1}$.
1451    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
1452    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p}$.
1453    ///
1454    /// If the output has a precision, it is `prec`.
1455    ///
1456    /// Special cases:
1457    /// - $f(0,k,p,m)=0.0$
1458    /// - $f(x,0,p,m)=\text{NaN}$
1459    /// - $f(x,1,p,m)=x$
1460    /// - $f(x,k,p,m)=\text{NaN}$ if $x<0$ and $k$ is even
1461    ///
1462    /// Overflow and underflow are possible when the exponent of $x$ exceeds $k$ times the maximum
1463    /// [`Float`] exponent in absolute value.
1464    ///
1465    /// If you know you'll be using `Nearest`, consider using [`Float::root_u_rational_prec`]
1466    /// instead.
1467    ///
1468    /// # Worst-case complexity
1469    /// $T(n) = O(n^{3/2} \log n \log\log n)$
1470    ///
1471    /// $M(n) = O(n \log n)$
1472    ///
1473    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
1474    ///
1475    /// # Panics
1476    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
1477    /// with the given precision.
1478    ///
1479    /// # Examples
1480    /// ```
1481    /// use malachite_base::rounding_modes::RoundingMode::*;
1482    /// use malachite_float::Float;
1483    /// use malachite_q::Rational;
1484    /// use std::cmp::Ordering::*;
1485    ///
1486    /// let (root, o) =
1487    ///     Float::root_u_rational_prec_round_ref(&Rational::from_signeds(3, 5), 3, 20, Floor);
1488    /// assert_eq!(root.to_string(), "0.84343243");
1489    /// assert_eq!(o, Less);
1490    ///
1491    /// let (root, o) =
1492    ///     Float::root_u_rational_prec_round_ref(&Rational::from_signeds(3, 5), 3, 20, Ceiling);
1493    /// assert_eq!(root.to_string(), "0.84343338");
1494    /// assert_eq!(o, Greater);
1495    /// ```
1496    pub fn root_u_rational_prec_round_ref(
1497        x: &Rational,
1498        k: u64,
1499        prec: u64,
1500        rm: RoundingMode,
1501    ) -> (Self, Ordering) {
1502        assert_ne!(prec, 0);
1503        if k == 0 {
1504            // The 0th root of anything is NaN (IEEE 754-2008).
1505            return (float_nan!(), Equal);
1506        } else if k == 1 {
1507            // x^(1/1) = x
1508            return Self::from_rational_prec_round_ref(x, prec, rm);
1509        }
1510        if *x == 0u32 {
1511            // 0^(1/k) = 0
1512            return (Self(Zero { sign: true }), Equal);
1513        }
1514        if *x < 0u32 && k.even() {
1515            // Negative x has no real kth root for even k.
1516            return (float_nan!(), Equal);
1517        }
1518        // A rational kth root is exact iff the numerator and denominator are both perfect kth
1519        // powers.
1520        if let Some(root) = x.checked_root(k) {
1521            return Self::from_rational_prec_round(root, prec, rm);
1522        }
1523        // The root of any other rational is irrational.
1524        assert_ne!(rm, Exact, "Inexact root");
1525        root_u_rational_generic(x, k, prec, rm)
1526    }
1527
1528    /// Takes the $k$th root of a [`Rational`], rounding the result to the nearest value of the
1529    /// specified precision and returning the result as a [`Float`]. The [`Rational`] is taken by
1530    /// value. An [`Ordering`] is also returned, indicating whether the rounded root is less than,
1531    /// equal to, or greater than the exact root. Although `NaN`s are not comparable to any
1532    /// [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
1533    ///
1534    /// If the root is equidistant from two [`Float`]s with the specified precision, the [`Float`]
1535    /// with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a description of
1536    /// the `Nearest` rounding mode.
1537    ///
1538    /// $$
1539    /// f(x,k,p) = \sqrt\[k\]{x}+\varepsilon.
1540    /// $$
1541    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
1542    ///   be 0.
1543    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, then $|\varepsilon| \leq 2^{\lfloor\log_2
1544    ///   |\sqrt\[k\]{x}|\rfloor-p}$.
1545    ///
1546    /// If the output has a precision, it is `prec`.
1547    ///
1548    /// Special cases:
1549    /// - $f(0,k,p)=0.0$
1550    /// - $f(x,0,p,m)=\text{NaN}$
1551    /// - $f(x,1,p,m)=x$
1552    /// - $f(x,k,p)=\text{NaN}$ if $x<0$ and $k$ is even
1553    ///
1554    /// Overflow and underflow are possible when the exponent of $x$ exceeds $k$ times the maximum
1555    /// [`Float`] exponent in absolute value.
1556    ///
1557    /// If you want to use a rounding mode other than `Nearest`, consider using
1558    /// [`Float::root_u_rational_prec_round`] instead.
1559    ///
1560    /// # Worst-case complexity
1561    /// $T(n) = O(n^{3/2} \log n \log\log n)$
1562    ///
1563    /// $M(n) = O(n \log n)$
1564    ///
1565    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
1566    ///
1567    /// # Panics
1568    /// Panics if `prec` is zero.
1569    ///
1570    /// # Examples
1571    /// ```
1572    /// use malachite_float::Float;
1573    /// use malachite_q::Rational;
1574    /// use std::cmp::Ordering::*;
1575    ///
1576    /// let (root, o) = Float::root_u_rational_prec(Rational::from_signeds(3, 5), 3, 20);
1577    /// assert_eq!(root.to_string(), "0.84343243");
1578    /// assert_eq!(o, Less);
1579    ///
1580    /// let (root, o) = Float::root_u_rational_prec(Rational::from_signeds(8, 27), 3, 10);
1581    /// assert_eq!(root.to_string(), "0.66699");
1582    /// assert_eq!(o, Greater);
1583    /// ```
1584    #[inline]
1585    pub fn root_u_rational_prec(x: Rational, k: u64, prec: u64) -> (Self, Ordering) {
1586        Self::root_u_rational_prec_round(x, k, prec, Nearest)
1587    }
1588
1589    /// Takes the $k$th root of a [`Rational`], rounding the result to the nearest value of the
1590    /// specified precision and returning the result as a [`Float`]. The [`Rational`] is taken by
1591    /// reference. An [`Ordering`] is also returned, indicating whether the rounded root is less
1592    /// than, equal to, or greater than the exact root. Although `NaN`s are not comparable to any
1593    /// [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
1594    ///
1595    /// If the root is equidistant from two [`Float`]s with the specified precision, the [`Float`]
1596    /// with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a description of
1597    /// the `Nearest` rounding mode.
1598    ///
1599    /// $$
1600    /// f(x,k,p) = \sqrt\[k\]{x}+\varepsilon.
1601    /// $$
1602    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
1603    ///   be 0.
1604    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, then $|\varepsilon| \leq 2^{\lfloor\log_2
1605    ///   |\sqrt\[k\]{x}|\rfloor-p}$.
1606    ///
1607    /// If the output has a precision, it is `prec`.
1608    ///
1609    /// Special cases:
1610    /// - $f(0,k,p)=0.0$
1611    /// - $f(x,0,p,m)=\text{NaN}$
1612    /// - $f(x,1,p,m)=x$
1613    /// - $f(x,k,p)=\text{NaN}$ if $x<0$ and $k$ is even
1614    ///
1615    /// Overflow and underflow are possible when the exponent of $x$ exceeds $k$ times the maximum
1616    /// [`Float`] exponent in absolute value.
1617    ///
1618    /// If you want to use a rounding mode other than `Nearest`, consider using
1619    /// [`Float::root_u_rational_prec_round`] instead.
1620    ///
1621    /// # Worst-case complexity
1622    /// $T(n) = O(n^{3/2} \log n \log\log n)$
1623    ///
1624    /// $M(n) = O(n \log n)$
1625    ///
1626    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
1627    ///
1628    /// # Panics
1629    /// Panics if `prec` is zero.
1630    ///
1631    /// # Examples
1632    /// ```
1633    /// use malachite_float::Float;
1634    /// use malachite_q::Rational;
1635    /// use std::cmp::Ordering::*;
1636    ///
1637    /// let (root, o) = Float::root_u_rational_prec_ref(&Rational::from_signeds(3, 5), 3, 20);
1638    /// assert_eq!(root.to_string(), "0.84343243");
1639    /// assert_eq!(o, Less);
1640    ///
1641    /// let (root, o) = Float::root_u_rational_prec_ref(&Rational::from_signeds(8, 27), 3, 10);
1642    /// assert_eq!(root.to_string(), "0.66699");
1643    /// assert_eq!(o, Greater);
1644    /// ```
1645    #[inline]
1646    pub fn root_u_rational_prec_ref(x: &Rational, k: u64, prec: u64) -> (Self, Ordering) {
1647        Self::root_u_rational_prec_round_ref(x, k, prec, Nearest)
1648    }
1649
1650    /// Takes the $k$th root of a [`Rational`], where $k$ may be negative, rounding the result to
1651    /// the specified precision and with the specified rounding mode and returning the result as a
1652    /// [`Float`]. The [`Rational`] is taken by value. An [`Ordering`] is also returned, indicating
1653    /// whether the rounded root is less than, equal to, or greater than the exact root. Although
1654    /// `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN` it also
1655    /// returns `Equal`.
1656    ///
1657    /// See [`RoundingMode`] for a description of the possible rounding modes.
1658    ///
1659    /// $$
1660    /// f(x,k,p,m) = \sqrt\[k\]{x}+\varepsilon.
1661    /// $$
1662    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
1663    ///   be 0.
1664    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
1665    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p+1}$.
1666    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
1667    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p}$.
1668    ///
1669    /// If the output has a precision, it is `prec`.
1670    ///
1671    /// Special cases for $k<0$ (for $k\geq 0$ the cases are those of the unsigned version):
1672    /// - $f(0,k,p,m)=\infty$
1673    /// - $f(x,k,p,m)=\text{NaN}$ if $x<0$ and $k$ is even
1674    ///
1675    /// Overflow and underflow are possible when the exponent of $x$ exceeds $|k|$ times the maximum
1676    /// [`Float`] exponent in absolute value.
1677    ///
1678    /// If you know you'll be using `Nearest`, consider using [`Float::root_s_rational_prec`]
1679    /// instead.
1680    ///
1681    /// # Worst-case complexity
1682    /// $T(n) = O(n^{3/2} \log n \log\log n)$
1683    ///
1684    /// $M(n) = O(n \log n)$
1685    ///
1686    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
1687    ///
1688    /// # Panics
1689    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
1690    /// with the given precision.
1691    ///
1692    /// # Examples
1693    /// ```
1694    /// use malachite_base::rounding_modes::RoundingMode::*;
1695    /// use malachite_float::Float;
1696    /// use malachite_q::Rational;
1697    /// use std::cmp::Ordering::*;
1698    ///
1699    /// let (root, o) =
1700    ///     Float::root_s_rational_prec_round(Rational::from_signeds(3, 5), -3, 20, Nearest);
1701    /// assert_eq!(root.to_string(), "1.1856308");
1702    /// assert_eq!(o, Less);
1703    /// ```
1704    #[allow(clippy::needless_pass_by_value)]
1705    #[inline]
1706    pub fn root_s_rational_prec_round(
1707        x: Rational,
1708        k: i64,
1709        prec: u64,
1710        rm: RoundingMode,
1711    ) -> (Self, Ordering) {
1712        Self::root_s_rational_prec_round_ref(&x, k, prec, rm)
1713    }
1714
1715    /// Takes the $k$th root of a [`Rational`], where $k$ may be negative, rounding the result to
1716    /// the specified precision and with the specified rounding mode and returning the result as a
1717    /// [`Float`]. The [`Rational`] is taken by reference. An [`Ordering`] is also returned,
1718    /// indicating whether the rounded root is less than, equal to, or greater than the exact root.
1719    /// Although `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN`
1720    /// it also returns `Equal`.
1721    ///
1722    /// See [`RoundingMode`] for a description of the possible rounding modes.
1723    ///
1724    /// $$
1725    /// f(x,k,p,m) = \sqrt\[k\]{x}+\varepsilon.
1726    /// $$
1727    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
1728    ///   be 0.
1729    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
1730    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p+1}$.
1731    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
1732    ///   2^{\lfloor\log_2 |\sqrt\[k\]{x}|\rfloor-p}$.
1733    ///
1734    /// If the output has a precision, it is `prec`.
1735    ///
1736    /// Special cases for $k<0$ (for $k\geq 0$ the cases are those of the unsigned version):
1737    /// - $f(0,k,p,m)=\infty$
1738    /// - $f(x,k,p,m)=\text{NaN}$ if $x<0$ and $k$ is even
1739    ///
1740    /// Overflow and underflow are possible when the exponent of $x$ exceeds $|k|$ times the maximum
1741    /// [`Float`] exponent in absolute value.
1742    ///
1743    /// If you know you'll be using `Nearest`, consider using [`Float::root_s_rational_prec`]
1744    /// instead.
1745    ///
1746    /// # Worst-case complexity
1747    /// $T(n) = O(n^{3/2} \log n \log\log n)$
1748    ///
1749    /// $M(n) = O(n \log n)$
1750    ///
1751    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
1752    ///
1753    /// # Panics
1754    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
1755    /// with the given precision.
1756    ///
1757    /// # Examples
1758    /// ```
1759    /// use malachite_base::rounding_modes::RoundingMode::*;
1760    /// use malachite_float::Float;
1761    /// use malachite_q::Rational;
1762    /// use std::cmp::Ordering::*;
1763    ///
1764    /// let (root, o) =
1765    ///     Float::root_s_rational_prec_round_ref(&Rational::from_signeds(3, 5), -3, 20, Nearest);
1766    /// assert_eq!(root.to_string(), "1.1856308");
1767    /// assert_eq!(o, Less);
1768    /// ```
1769    pub fn root_s_rational_prec_round_ref(
1770        x: &Rational,
1771        k: i64,
1772        prec: u64,
1773        rm: RoundingMode,
1774    ) -> (Self, Ordering) {
1775        if k >= 0 {
1776            return Self::root_u_rational_prec_round_ref(x, k.unsigned_abs(), prec, rm);
1777        }
1778        assert_ne!(prec, 0);
1779        if *x == 0u32 {
1780            // 0^(1/k) = +Infinity for k < 0
1781            return (Self(Infinity { sign: true }), Equal);
1782        }
1783        if *x < 0u32 && k.even() {
1784            // Negative x has no real kth root for even k.
1785            return (float_nan!(), Equal);
1786        }
1787        // x^(1/k) = (1/x)^(1/-k), and the reciprocal of a rational is exact.
1788        Self::root_u_rational_prec_round(x.reciprocal(), k.unsigned_abs(), prec, rm)
1789    }
1790
1791    /// Takes the $k$th root of a [`Rational`], where $k$ may be negative, rounding the result to
1792    /// the nearest value of the specified precision and returning the result as a [`Float`]. The
1793    /// [`Rational`] is taken by value. An [`Ordering`] is also returned, indicating whether the
1794    /// rounded root is less than, equal to, or greater than the exact root. Although `NaN`s are not
1795    /// comparable to any [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
1796    ///
1797    /// If the root is equidistant from two [`Float`]s with the specified precision, the [`Float`]
1798    /// with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a description of
1799    /// the `Nearest` rounding mode.
1800    ///
1801    /// $$
1802    /// f(x,k,p) = \sqrt\[k\]{x}+\varepsilon.
1803    /// $$
1804    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
1805    ///   be 0.
1806    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, then $|\varepsilon| \leq 2^{\lfloor\log_2
1807    ///   |\sqrt\[k\]{x}|\rfloor-p}$.
1808    ///
1809    /// If the output has a precision, it is `prec`.
1810    ///
1811    /// Special cases for $k<0$ (for $k\geq 0$ the cases are those of the unsigned version):
1812    /// - $f(0,k,p)=\infty$
1813    /// - $f(x,k,p)=\text{NaN}$ if $x<0$ and $k$ is even
1814    ///
1815    /// Overflow and underflow are possible when the exponent of $x$ exceeds $|k|$ times the maximum
1816    /// [`Float`] exponent in absolute value.
1817    ///
1818    /// If you want to use a rounding mode other than `Nearest`, consider using
1819    /// [`Float::root_s_rational_prec_round`] instead.
1820    ///
1821    /// # Worst-case complexity
1822    /// $T(n) = O(n^{3/2} \log n \log\log n)$
1823    ///
1824    /// $M(n) = O(n \log n)$
1825    ///
1826    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
1827    ///
1828    /// # Panics
1829    /// Panics if `prec` is zero.
1830    ///
1831    /// # Examples
1832    /// ```
1833    /// use malachite_float::Float;
1834    /// use malachite_q::Rational;
1835    /// use std::cmp::Ordering::*;
1836    ///
1837    /// let (root, o) = Float::root_s_rational_prec(Rational::from_signeds(27, 8), -3, 10);
1838    /// assert_eq!(root.to_string(), "0.66699");
1839    /// assert_eq!(o, Greater);
1840    /// ```
1841    #[inline]
1842    pub fn root_s_rational_prec(x: Rational, k: i64, prec: u64) -> (Self, Ordering) {
1843        Self::root_s_rational_prec_round(x, k, prec, Nearest)
1844    }
1845
1846    /// Takes the $k$th root of a [`Rational`], where $k$ may be negative, rounding the result to
1847    /// the nearest value of the specified precision and returning the result as a [`Float`]. The
1848    /// [`Rational`] is taken by reference. An [`Ordering`] is also returned, indicating whether the
1849    /// rounded root is less than, equal to, or greater than the exact root. Although `NaN`s are not
1850    /// comparable to any [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
1851    ///
1852    /// If the root is equidistant from two [`Float`]s with the specified precision, the [`Float`]
1853    /// with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a description of
1854    /// the `Nearest` rounding mode.
1855    ///
1856    /// $$
1857    /// f(x,k,p) = \sqrt\[k\]{x}+\varepsilon.
1858    /// $$
1859    /// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to
1860    ///   be 0.
1861    /// - If $\sqrt\[k\]{x}$ is finite and nonzero, then $|\varepsilon| \leq 2^{\lfloor\log_2
1862    ///   |\sqrt\[k\]{x}|\rfloor-p}$.
1863    ///
1864    /// If the output has a precision, it is `prec`.
1865    ///
1866    /// Special cases for $k<0$ (for $k\geq 0$ the cases are those of the unsigned version):
1867    /// - $f(0,k,p)=\infty$
1868    /// - $f(x,k,p)=\text{NaN}$ if $x<0$ and $k$ is even
1869    ///
1870    /// Overflow and underflow are possible when the exponent of $x$ exceeds $|k|$ times the maximum
1871    /// [`Float`] exponent in absolute value.
1872    ///
1873    /// If you want to use a rounding mode other than `Nearest`, consider using
1874    /// [`Float::root_s_rational_prec_round`] instead.
1875    ///
1876    /// # Worst-case complexity
1877    /// $T(n) = O(n^{3/2} \log n \log\log n)$
1878    ///
1879    /// $M(n) = O(n \log n)$
1880    ///
1881    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
1882    ///
1883    /// # Panics
1884    /// Panics if `prec` is zero.
1885    ///
1886    /// # Examples
1887    /// ```
1888    /// use malachite_float::Float;
1889    /// use malachite_q::Rational;
1890    /// use std::cmp::Ordering::*;
1891    ///
1892    /// let (root, o) = Float::root_s_rational_prec_ref(&Rational::from_signeds(27, 8), -3, 10);
1893    /// assert_eq!(root.to_string(), "0.66699");
1894    /// assert_eq!(o, Greater);
1895    /// ```
1896    #[inline]
1897    pub fn root_s_rational_prec_ref(x: &Rational, k: i64, prec: u64) -> (Self, Ordering) {
1898        Self::root_s_rational_prec_round_ref(x, k, prec, Nearest)
1899    }
1900}
1901
1902impl Root<u64> for Float {
1903    type Output = Self;
1904
1905    /// Takes the $k$th root of a [`Float`], rounding the result to the nearest value at the
1906    /// precision of the input. The [`Float`] is taken by value.
1907    ///
1908    /// If the root is equidistant from two [`Float`]s with that precision, the [`Float`] with fewer
1909    /// 1s in its binary expansion is chosen. See [`RoundingMode`] for a description of the
1910    /// `Nearest` rounding mode.
1911    ///
1912    /// See the [`Float::root_u_prec_round`] documentation for information on special cases.
1913    ///
1914    /// If you want to specify an output precision, consider using [`Float::root_u_prec`] instead.
1915    /// If you want to specify the output precision and the rounding mode, consider using
1916    /// [`Float::root_u_prec_round`] instead.
1917    ///
1918    /// # Worst-case complexity
1919    /// $T(n) = O(n^{3/2} \log n \log\log n)$
1920    ///
1921    /// $M(n) = O(n \log n)$
1922    ///
1923    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.    ///
1924    /// # Examples
1925    /// ```
1926    /// use malachite_base::num::arithmetic::traits::Root;
1927    /// use malachite_float::Float;
1928    ///
1929    /// assert_eq!(Float::from(27.0).root(3u64).to_string(), "3.00");
1930    /// ```
1931    #[inline]
1932    fn root(self, pow: u64) -> Self {
1933        let prec = self.significant_bits();
1934        self.root_u_prec(pow, prec).0
1935    }
1936}
1937
1938impl Root<u64> for &Float {
1939    type Output = Float;
1940
1941    /// Takes the $k$th root of a [`Float`], rounding the result to the nearest value at the
1942    /// precision of the input. The [`Float`] is taken by reference.
1943    ///
1944    /// If the root is equidistant from two [`Float`]s with that precision, the [`Float`] with fewer
1945    /// 1s in its binary expansion is chosen. See [`RoundingMode`] for a description of the
1946    /// `Nearest` rounding mode.
1947    ///
1948    /// See the [`Float::root_u_prec_round`] documentation for information on special cases.
1949    ///
1950    /// If you want to specify an output precision, consider using [`Float::root_u_prec`] instead.
1951    /// If you want to specify the output precision and the rounding mode, consider using
1952    /// [`Float::root_u_prec_round`] instead.
1953    ///
1954    /// # Worst-case complexity
1955    /// $T(n) = O(n^{3/2} \log n \log\log n)$
1956    ///
1957    /// $M(n) = O(n \log n)$
1958    ///
1959    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.    ///
1960    /// # Examples
1961    /// ```
1962    /// use malachite_base::num::arithmetic::traits::Root;
1963    /// use malachite_float::Float;
1964    ///
1965    /// assert_eq!((&Float::from(27.0)).root(3u64).to_string(), "3.00");
1966    /// ```
1967    #[inline]
1968    fn root(self, pow: u64) -> Float {
1969        self.root_u_prec_ref(pow, self.significant_bits()).0
1970    }
1971}
1972
1973impl RootAssign<u64> for Float {
1974    /// Takes the $k$th root of a [`Float`] in place, rounding the result to the nearest value at
1975    /// the precision of the input.
1976    ///
1977    /// If the root is equidistant from two [`Float`]s with that precision, the [`Float`] with fewer
1978    /// 1s in its binary expansion is chosen. See [`RoundingMode`] for a description of the
1979    /// `Nearest` rounding mode.
1980    ///
1981    /// See the [`Float::root_u_prec_round`] documentation for information on special cases.
1982    ///
1983    /// If you want to specify an output precision, consider using [`Float::root_u_prec`] instead.
1984    /// If you want to specify the output precision and the rounding mode, consider using
1985    /// [`Float::root_u_prec_round`] instead.
1986    ///
1987    /// # Worst-case complexity
1988    /// $T(n) = O(n^{3/2} \log n \log\log n)$
1989    ///
1990    /// $M(n) = O(n \log n)$
1991    ///
1992    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.    ///
1993    /// # Examples
1994    /// ```
1995    /// use malachite_base::num::arithmetic::traits::RootAssign;
1996    /// use malachite_float::Float;
1997    ///
1998    /// let mut x = Float::from(32.0);
1999    /// x.root_assign(5u64);
2000    /// assert_eq!(x.to_string(), "2.0");
2001    /// ```
2002    #[inline]
2003    fn root_assign(&mut self, pow: u64) {
2004        let prec = self.significant_bits();
2005        self.root_u_prec_round_assign(pow, prec, Nearest);
2006    }
2007}
2008
2009impl Root<i64> for Float {
2010    type Output = Self;
2011
2012    /// Takes the $k$th root of a [`Float`], where $k$ may be negative, rounding the result to the
2013    /// nearest value at the precision of the input. The [`Float`] is taken by value.
2014    ///
2015    /// If the root is equidistant from two [`Float`]s with that precision, the [`Float`] with fewer
2016    /// 1s in its binary expansion is chosen. See [`RoundingMode`] for a description of the
2017    /// `Nearest` rounding mode.
2018    ///
2019    /// See the [`Float::root_s_prec_round`] documentation for information on special cases.
2020    ///
2021    /// If you want to specify an output precision, consider using [`Float::root_s_prec`] instead.
2022    /// If you want to specify the output precision and the rounding mode, consider using
2023    /// [`Float::root_s_prec_round`] instead.
2024    ///
2025    /// # Worst-case complexity
2026    /// $T(n) = O(n^{3/2} \log n \log\log n)$
2027    ///
2028    /// $M(n) = O(n \log n)$
2029    ///
2030    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.    ///
2031    /// # Examples
2032    /// ```
2033    /// use malachite_base::num::arithmetic::traits::Root;
2034    /// use malachite_float::Float;
2035    ///
2036    /// assert_eq!(Float::from(8.0).root(-3i64).to_string(), "0.50");
2037    /// ```
2038    #[inline]
2039    fn root(self, pow: i64) -> Self {
2040        let prec = self.significant_bits();
2041        self.root_s_prec(pow, prec).0
2042    }
2043}
2044
2045impl Root<i64> for &Float {
2046    type Output = Float;
2047
2048    /// Takes the $k$th root of a [`Float`], where $k$ may be negative, rounding the result to the
2049    /// nearest value at the precision of the input. The [`Float`] is taken by reference.
2050    ///
2051    /// If the root is equidistant from two [`Float`]s with that precision, the [`Float`] with fewer
2052    /// 1s in its binary expansion is chosen. See [`RoundingMode`] for a description of the
2053    /// `Nearest` rounding mode.
2054    ///
2055    /// See the [`Float::root_s_prec_round`] documentation for information on special cases.
2056    ///
2057    /// If you want to specify an output precision, consider using [`Float::root_s_prec`] instead.
2058    /// If you want to specify the output precision and the rounding mode, consider using
2059    /// [`Float::root_s_prec_round`] instead.
2060    ///
2061    /// # Worst-case complexity
2062    /// $T(n) = O(n^{3/2} \log n \log\log n)$
2063    ///
2064    /// $M(n) = O(n \log n)$
2065    ///
2066    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.    ///
2067    /// # Examples
2068    /// ```
2069    /// use malachite_base::num::arithmetic::traits::Root;
2070    /// use malachite_float::Float;
2071    ///
2072    /// assert_eq!((&Float::from(8.0)).root(-3i64).to_string(), "0.50");
2073    /// ```
2074    #[inline]
2075    fn root(self, pow: i64) -> Float {
2076        self.root_s_prec_ref(pow, self.significant_bits()).0
2077    }
2078}
2079
2080impl RootAssign<i64> for Float {
2081    /// Takes the $k$th root of a [`Float`] in place, where $k$ may be negative, rounding the result
2082    /// to the nearest value at the precision of the input.
2083    ///
2084    /// If the root is equidistant from two [`Float`]s with that precision, the [`Float`] with fewer
2085    /// 1s in its binary expansion is chosen. See [`RoundingMode`] for a description of the
2086    /// `Nearest` rounding mode.
2087    ///
2088    /// See the [`Float::root_s_prec_round`] documentation for information on special cases.
2089    ///
2090    /// If you want to specify an output precision, consider using [`Float::root_s_prec`] instead.
2091    /// If you want to specify the output precision and the rounding mode, consider using
2092    /// [`Float::root_s_prec_round`] instead.
2093    ///
2094    /// # Worst-case complexity
2095    /// $T(n) = O(n^{3/2} \log n \log\log n)$
2096    ///
2097    /// $M(n) = O(n \log n)$
2098    ///
2099    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.    ///
2100    /// # Examples
2101    /// ```
2102    /// use malachite_base::num::arithmetic::traits::RootAssign;
2103    /// use malachite_float::Float;
2104    ///
2105    /// let mut x = Float::from(4.0);
2106    /// x.root_assign(-2i64);
2107    /// assert_eq!(x.to_string(), "0.50");
2108    /// ```
2109    #[inline]
2110    fn root_assign(&mut self, pow: i64) {
2111        let prec = self.significant_bits();
2112        self.root_s_prec_round_assign(pow, prec, Nearest);
2113    }
2114}
2115
2116/// Takes the $k$th root of a primitive float. The result is correctly rounded. In particular,
2117/// `primitive_float_root_u(x, 3)` is a correctly-rounded cube root, unlike the standard library's
2118/// `cbrt`.
2119///
2120/// $$
2121/// f(x,k) = \sqrt\[k\]{x}+\varepsilon.
2122/// $$
2123/// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be
2124///   0.
2125/// - If $\sqrt\[k\]{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
2126///   |\sqrt\[k\]{x}|\rfloor-p}$, where $p$ is the precision of the output (typically 24 if `T` is a
2127///   [`f32`] and 53 if `T` is a [`f64`], but less if the output is subnormal).
2128///
2129/// Special cases: see [`Float::root_u_prec_round`].
2130///
2131/// # Worst-case complexity
2132/// $T(n) = O(n^{3/2} \log n \log\log n)$
2133///
2134/// $M(n) = O(n \log n)$
2135///
2136/// where $T$ is time, $M$ is additional memory, and $n$ is the precision of the output.
2137///
2138/// # Examples
2139/// ```
2140/// use malachite_base::num::float::NiceFloat;
2141/// use malachite_float::float::arithmetic::root::primitive_float_root_u;
2142///
2143/// assert_eq!(
2144///     NiceFloat(primitive_float_root_u(27.0f64, 3)),
2145///     NiceFloat(3.0)
2146/// );
2147/// assert_eq!(
2148///     NiceFloat(primitive_float_root_u(2.0f64, 3)),
2149///     NiceFloat(1.2599210498948732)
2150/// );
2151/// ```
2152#[inline]
2153#[allow(clippy::type_repetition_in_bounds)]
2154pub fn primitive_float_root_u<T: PrimitiveFloat>(x: T, k: u64) -> T
2155where
2156    Float: From<T> + PartialOrd<T>,
2157    for<'a> T: ExactFrom<&'a Float> + RoundingFrom<&'a Float>,
2158{
2159    emulate_float_to_float_fn(|f, prec| Float::root_u_prec(f, k, prec), x)
2160}
2161
2162/// Takes the $k$th root of a primitive float, where $k$ may be negative. The result is correctly
2163/// rounded.
2164///
2165/// $$
2166/// f(x,k) = \sqrt\[k\]{x}+\varepsilon.
2167/// $$
2168/// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be
2169///   0.
2170/// - If $\sqrt\[k\]{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
2171///   |\sqrt\[k\]{x}|\rfloor-p}$, where $p$ is the precision of the output (typically 24 if `T` is a
2172///   [`f32`] and 53 if `T` is a [`f64`], but less if the output is subnormal).
2173///
2174/// Special cases: see [`Float::root_s_prec_round`].
2175///
2176/// # Worst-case complexity
2177/// $T(n) = O(n^{3/2} \log n \log\log n)$
2178///
2179/// $M(n) = O(n \log n)$
2180///
2181/// where $T$ is time, $M$ is additional memory, and $n$ is the precision of the output.
2182///
2183/// # Examples
2184/// ```
2185/// use malachite_base::num::float::NiceFloat;
2186/// use malachite_float::float::arithmetic::root::primitive_float_root_s;
2187///
2188/// assert_eq!(
2189///     NiceFloat(primitive_float_root_s(8.0f64, -3)),
2190///     NiceFloat(0.5)
2191/// );
2192/// assert_eq!(
2193///     NiceFloat(primitive_float_root_s(2.0f64, -3)),
2194///     NiceFloat(0.7937005259840998)
2195/// );
2196/// ```
2197#[inline]
2198#[allow(clippy::type_repetition_in_bounds)]
2199pub fn primitive_float_root_s<T: PrimitiveFloat>(x: T, k: i64) -> T
2200where
2201    Float: From<T> + PartialOrd<T>,
2202    for<'a> T: ExactFrom<&'a Float> + RoundingFrom<&'a Float>,
2203{
2204    emulate_float_to_float_fn(|f, prec| Float::root_s_prec(f, k, prec), x)
2205}
2206
2207/// Takes the $k$th root of a [`Rational`], returning the result as a primitive float. The result is
2208/// correctly rounded.
2209///
2210/// $$
2211/// f(x,k) = \sqrt\[k\]{x}+\varepsilon.
2212/// $$
2213/// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be
2214///   0.
2215/// - If $\sqrt\[k\]{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
2216///   |\sqrt\[k\]{x}|\rfloor-p}$, where $p$ is the precision of the output (typically 24 if `T` is a
2217///   [`f32`] and 53 if `T` is a [`f64`], but less if the output is subnormal).
2218///
2219/// Special cases: see [`Float::root_u_rational_prec_round`].
2220///
2221/// # Worst-case complexity
2222/// $T(n) = O(n^{3/2} \log n \log\log n)$
2223///
2224/// $M(n) = O(n \log n)$
2225///
2226/// where $T$ is time, $M$ is additional memory, and $n$ is the precision of the output.
2227///
2228/// # Examples
2229/// ```
2230/// use malachite_base::num::float::NiceFloat;
2231/// use malachite_float::float::arithmetic::root::primitive_float_root_u_rational;
2232/// use malachite_q::Rational;
2233///
2234/// assert_eq!(
2235///     NiceFloat(primitive_float_root_u_rational::<f32>(
2236///         &Rational::from_signeds(8, 27),
2237///         3
2238///     )),
2239///     NiceFloat(0.6666667)
2240/// );
2241/// ```
2242#[inline]
2243#[allow(clippy::type_repetition_in_bounds)]
2244pub fn primitive_float_root_u_rational<T: PrimitiveFloat>(x: &Rational, k: u64) -> T
2245where
2246    Float: PartialOrd<T>,
2247    for<'a> T: ExactFrom<&'a Float> + RoundingFrom<&'a Float>,
2248{
2249    emulate_rational_to_float_fn(|q, prec| Float::root_u_rational_prec_ref(q, k, prec), x)
2250}
2251
2252/// Takes the $k$th root of a [`Rational`], where $k$ may be negative, returning the result as a
2253/// primitive float. The result is correctly rounded.
2254///
2255/// $$
2256/// f(x,k) = \sqrt\[k\]{x}+\varepsilon.
2257/// $$
2258/// - If $\sqrt\[k\]{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be
2259///   0.
2260/// - If $\sqrt\[k\]{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
2261///   |\sqrt\[k\]{x}|\rfloor-p}$, where $p$ is the precision of the output (typically 24 if `T` is a
2262///   [`f32`] and 53 if `T` is a [`f64`], but less if the output is subnormal).
2263///
2264/// Special cases: see [`Float::root_s_rational_prec_round`].
2265///
2266/// # Worst-case complexity
2267/// $T(n) = O(n^{3/2} \log n \log\log n)$
2268///
2269/// $M(n) = O(n \log n)$
2270///
2271/// where $T$ is time, $M$ is additional memory, and $n$ is the precision of the output.
2272///
2273/// # Examples
2274/// ```
2275/// use malachite_base::num::float::NiceFloat;
2276/// use malachite_float::float::arithmetic::root::primitive_float_root_s_rational;
2277/// use malachite_q::Rational;
2278///
2279/// assert_eq!(
2280///     NiceFloat(primitive_float_root_s_rational::<f32>(
2281///         &Rational::from(8),
2282///         -3
2283///     )),
2284///     NiceFloat(0.5)
2285/// );
2286/// ```
2287#[inline]
2288#[allow(clippy::type_repetition_in_bounds)]
2289pub fn primitive_float_root_s_rational<T: PrimitiveFloat>(x: &Rational, k: i64) -> T
2290where
2291    Float: PartialOrd<T>,
2292    for<'a> T: ExactFrom<&'a Float> + RoundingFrom<&'a Float>,
2293{
2294    emulate_rational_to_float_fn(|q, prec| Float::root_s_rational_prec_ref(q, k, prec), x)
2295}