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