Skip to main content

malachite_float/float/arithmetic/
ln.rs

1// Copyright © 2026 Mikhail Hogrefe
2//
3// Uses code adopted from the GNU MPFR Library.
4//
5//      Copyright 1999-2026 Free Software Foundation, Inc.
6//
7//      Contributed by the Pascaline 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::{Finite, Infinity, NaN, Zero};
16use crate::float::basic::extended::ExtendedFloat;
17use crate::{
18    Float, emulate_float_to_float_fn, emulate_rational_to_float_fn, float_either_zero,
19    float_infinity, float_nan, float_negative_infinity, float_zero, floor_and_ceiling,
20    significand_bits,
21};
22use alloc::vec;
23use core::cmp::Ordering::{self, *};
24use core::mem::{swap, take};
25use malachite_base::num::arithmetic::traits::{
26    Abs, AddMulShl, Agm, CeilingLogBase2, IsPowerOf2, Ln, LnAssign, NegAssign, Parity, PowerOf2,
27    Sign,
28};
29use malachite_base::num::basic::floats::PrimitiveFloat;
30use malachite_base::num::basic::integers::PrimitiveInt;
31use malachite_base::num::basic::traits::{NegativeInfinity, One, Zero as ZeroTrait};
32use malachite_base::num::conversion::traits::{ExactFrom, RoundingFrom, SaturatingFrom};
33use malachite_base::num::logic::traits::SignificantBits;
34use malachite_base::rounding_modes::RoundingMode::{self, *};
35use malachite_nz::integer::Integer;
36use malachite_nz::natural::arithmetic::float::round::float_can_round;
37use malachite_nz::platform::Limb;
38use malachite_q::Rational;
39
40// The computation of log(x) is done using the formula: if we want p bits of the result,
41// ```
42//                    pi
43//      log(x) ~ ------------- - m log 2
44//               2 AG(1,4 / s)
45// ```
46// where s = x 2^m > 2^(p/2).
47//
48// More precisely, if F(x) = int(1 / ln(1 - (1 - x ^ 2) * sin(t) ^ 2), t = 0..pi / 2), then for s >=
49// 1.26 we have log(s) < F(4 / s) < log(s) * (1 + 4 / s ^ 2) from which we deduce pi / 2 / AG(1, 4 /
50// s) * (1 - 4 / s ^ 2) < log(s) < pi / 2 / AG(1, 4 / s) so the relative error 4 / s ^ 2 is < 4 / 2
51// ^ p i.e. 4 ulps.
52//
53// When `x` lies within a sliver of 1 -- `|x - 1|` within a few binades of the smallest positive
54// `Float` -- returns `x - 1`, and otherwise `None`. For such `x`, `log(x) ~ x - 1` can fall below
55// the smallest positive `Float`: the working subtractions in the log loops would flush to zero or
56// clamp, and the rounding test could never certify a result, so the callers delegate to the
57// `1_plus_x` functions, whose tiny-argument paths handle the underflow region correctly. Reaching
58// the sliver requires an input precision of nearly 2^30 bits, so for every other `x` the guard
59// costs only an exponent-and-precision test; the subtraction (performed only past that test) is
60// exact, since `x` is within `(1/2, 2)`. Brackets of ln(1 + e) for an exact nonzero Rational e with
61// |e| < 1/2, as exact Rationals, to a relative accuracy of about 2^-wprec. Uses the Mercator series
62// ln(1 + e) = sum_{k>=1} (-1)^(k+1) e^k / k. For e > 0 the terms strictly alternate in sign and
63// decrease in magnitude, so consecutive partial sums bracket the value; for e < 0 every term is
64// negative, so a partial sum is an upper bound and the remainder after it is bounded in magnitude
65// by |e|^(k+1) / ((k + 1)(1 - |e|)). Unlike the atanh form, this needs no `e / (2 + e)` division,
66// which is the dominant cost when e is a sub-`MIN` sliver (a ~128-MB Rational).
67pub(crate) fn ln_1_plus_rational_brackets(e: &Rational, wprec: u64) -> (Rational, Rational) {
68    let negative = *e < 0u32;
69    let mut pow = e.clone(); // e^k
70    let mut s = e.clone(); // partial sum S_k
71    let mut k = 1u64;
72    loop {
73        pow *= e; // e^(k+1)
74        k += 1;
75        let mut term = &pow / Rational::from(k); // (-1)^(k+1) e^k / k, up to sign
76        if k.even() {
77            term.neg_assign();
78        }
79        let s_next = &s + &term; // S_{k+1}
80        let (lo, hi) = if negative {
81            // S_{k+1} is an upper bound; the remainder is bounded in magnitude by |e|^(k+2) / ((k +
82            // 2)(1 - |e|)), and 1 - |e| = 1 + e for e < 0.
83            let bound = -((&pow * e) / (Rational::from(k + 1) * (Rational::ONE + e))).abs();
84            (&s_next + &bound, s_next.clone())
85        } else if s < s_next {
86            (s.clone(), s_next.clone())
87        } else {
88            (s_next.clone(), s.clone())
89        };
90        s = s_next;
91        let width = &hi - &lo;
92        if width == 0u32
93            || width.floor_log_base_2_abs() < lo.floor_log_base_2_abs() - i64::exact_from(wprec) - 2
94        {
95            return (lo, hi);
96        }
97    }
98}
99
100pub(crate) enum SliverOfOne {
101    // `x` is not within a sliver of 1; use the ordinary logarithm path.
102    No,
103    // `x = 1 + d` with `d` representable; compute the logarithm via the `1_plus_x` form.
104    Representable(Float),
105    // `x` is so close to 1 that its logarithm falls at or below the smallest positive `Float`. The
106    // subtraction `x - 1` cannot be represented (it flushes to zero for `x > 1`, or clamps to the
107    // minimum magnitude for `x < 1`), so the caller computes the underflowing result via the
108    // exact-`Rational` logarithm of `x` (whose Rational-argument path has no exponent range).
109    Underflow,
110}
111
112pub(crate) fn sliver_of_one(x: &Float) -> SliverOfOne {
113    let e = i64::from(x.get_exponent().unwrap());
114    if (e == 0 || e == 1) && x.get_prec().unwrap() >= Float::NEAR_ONE_MAX_PREC {
115        let (mut d, o) = x.sub_prec_round_ref_val(Float::ONE, x.get_prec().unwrap() + 1, Floor);
116        if o != Equal {
117            // `x - 1` fell below the smallest positive `Float`, so `ln(x) ~ x - 1` underflows.
118            return SliverOfOne::Underflow;
119        }
120        if i64::from(d.get_exponent().unwrap()) <= Float::MIN_EXPONENT_PLUS_4_I64 {
121            // Shed the trailing zeros inherited from the subtraction's requested precision: d's
122            // true significant span is small, and the inflated precision would defeat the
123            // `1_plus_x` functions' round-near-x shortcut (a significand padded with ~2^30 trailing
124            // zeros fails their rounding test).
125            let sig = d.significand_ref().unwrap();
126            let min_prec = significand_bits(sig) - sig.trailing_zeros().unwrap();
127            let o = d.set_prec_round(min_prec, Floor);
128            debug_assert_eq!(o, Equal);
129            return SliverOfOne::Representable(d);
130        }
131    }
132    SliverOfOne::No
133}
134
135// This is mpfr_log from log.c, MPFR 4.2.0.
136fn ln_prec_round_normal_ref(x: &Float, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
137    if *x == 1u32 {
138        return (Float::ZERO, Equal);
139    }
140    // ln(x) for x in a sliver of 1 can fall below the smallest positive Float; the 1-plus-x form
141    // handles that underflow region.
142    match sliver_of_one(x) {
143        SliverOfOne::Representable(d) => return d.ln_1_plus_x_prec_round(prec, rm),
144        SliverOfOne::Underflow => {
145            return Float::ln_rational_prec_round(Rational::exact_from(x), prec, rm);
146        }
147        SliverOfOne::No => {}
148    }
149    assert_ne!(rm, Exact, "Inexact ln");
150    let x_exp = i64::from(x.get_exponent().unwrap());
151    // use initial precision about q + 2 * lg(q) + cte
152    let mut working_prec = prec + (prec.ceiling_log_base_2() << 1) + 10;
153    let mut increment = Limb::WIDTH;
154    let mut previous_m = 0;
155    let mut x = x.clone();
156    loop {
157        // Calculus of m (depends on p)
158        let m = i64::exact_from((working_prec + 3) >> 1)
159            .checked_sub(x_exp)
160            .unwrap();
161        x <<= m - previous_m;
162        previous_m = m;
163        assert!(x.is_normal());
164        let tmp2 = Float::pi_prec(working_prec).0
165            / (Float::ONE.agm(
166                const { Float::const_from_unsigned(4) }
167                    .div_prec_round_val_ref(&x, working_prec, Floor)
168                    .0,
169            ) << 1u32);
170        let exp2 = tmp2.get_exponent();
171        let tmp1 = tmp2
172            - Float::ln_2_prec(working_prec)
173                .0
174                .mul_prec(Float::from(m), working_prec)
175                .0;
176        if let (Some(exp1), Some(exp2)) = (tmp1.get_exponent(), exp2) {
177            let cancel = u64::saturating_from(exp2 - exp1);
178            // we have 7 ulps of error from the above roundings, 4 ulps from the 4 / s ^ 2 second
179            // order term, plus the canceled bits
180            if float_can_round(
181                tmp1.significand_ref().unwrap(),
182                working_prec.saturating_sub(cancel).saturating_sub(4),
183                prec,
184                rm,
185            ) {
186                return Float::from_float_prec_round(tmp1, prec, rm);
187            }
188            working_prec += cancel + working_prec.ceiling_log_base_2();
189        } else {
190            working_prec += working_prec.ceiling_log_base_2();
191        }
192        working_prec += increment;
193        increment = working_prec >> 1;
194    }
195}
196
197// This is mpfr_log from log.c, MPFR 4.2.0.
198fn ln_prec_round_normal(mut x: Float, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
199    if x == 1u32 {
200        return (Float::ZERO, Equal);
201    }
202    // ln(x) for x in a sliver of 1 can fall below the smallest positive Float; the 1-plus-x form
203    // handles that underflow region.
204    match sliver_of_one(&x) {
205        SliverOfOne::Representable(d) => return d.ln_1_plus_x_prec_round(prec, rm),
206        SliverOfOne::Underflow => {
207            return Float::ln_rational_prec_round(Rational::exact_from(&x), prec, rm);
208        }
209        SliverOfOne::No => {}
210    }
211    assert_ne!(rm, Exact, "Inexact ln");
212    let x_exp = i64::from(x.get_exponent().unwrap());
213    // use initial precision about q + 2 * lg(q) + cte
214    let mut working_prec = prec + (prec.ceiling_log_base_2() << 1) + 10;
215    let mut increment = Limb::WIDTH;
216    let mut previous_m = 0;
217    loop {
218        // Calculus of m (depends on p)
219        let m = i64::exact_from((working_prec + 3) >> 1)
220            .checked_sub(x_exp)
221            .unwrap();
222        x <<= m - previous_m;
223        previous_m = m;
224        assert!(x.is_normal());
225        let tmp2 = Float::pi_prec(working_prec).0
226            / (Float::ONE.agm(
227                const { Float::const_from_unsigned(4) }
228                    .div_prec_round_val_ref(&x, working_prec, Floor)
229                    .0,
230            ) << 1u32);
231        let exp2 = tmp2.get_exponent();
232        let tmp1 = tmp2
233            - Float::ln_2_prec(working_prec)
234                .0
235                .mul_prec(Float::from(m), working_prec)
236                .0;
237        if let (Some(exp1), Some(exp2)) = (tmp1.get_exponent(), exp2) {
238            let cancel = u64::saturating_from(exp2 - exp1);
239            // we have 7 ulps of error from the above roundings, 4 ulps from the 4 / s ^ 2 second
240            // order term, plus the canceled bits
241            if float_can_round(
242                tmp1.significand_ref().unwrap(),
243                working_prec.saturating_sub(cancel).saturating_sub(4),
244                prec,
245                rm,
246            ) {
247                return Float::from_float_prec_round(tmp1, prec, rm);
248            }
249            working_prec += cancel + working_prec.ceiling_log_base_2();
250        } else {
251            working_prec += working_prec.ceiling_log_base_2();
252        }
253        working_prec += increment;
254        increment = working_prec >> 1;
255    }
256}
257
258pub(crate) fn ln_prec_round_normal_extended(
259    x: ExtendedFloat,
260    prec: u64,
261    rm: RoundingMode,
262) -> (Float, Ordering) {
263    if x.exp == 1 && x.x.is_power_of_2() {
264        return (Float::ZERO, Equal);
265    }
266    assert_ne!(rm, Exact, "Inexact ln");
267    let x_exp = x.exp;
268    // use initial precision about q + 2 * lg(q) + cte
269    let mut working_prec = prec + (prec.ceiling_log_base_2() << 1) + 10;
270    let mut increment = Limb::WIDTH;
271    let mut m = i64::exact_from((working_prec + 3) >> 1)
272        .checked_sub(x.exp)
273        .unwrap();
274    let mut previous_m = m;
275    let mut x = Float::exact_from(x << m);
276    let mut first = true;
277    loop {
278        if first {
279            first = false;
280        } else {
281            // Calculus of m (depends on p)
282            m = i64::exact_from((working_prec + 3) >> 1)
283                .checked_sub(x_exp)
284                .unwrap();
285            x <<= m - previous_m;
286            previous_m = m;
287        }
288        assert!(x.is_normal());
289        let tmp2 = Float::pi_prec(working_prec).0
290            / (Float::ONE.agm(
291                const { Float::const_from_unsigned(4) }
292                    .div_prec_round_val_ref(&x, working_prec, Floor)
293                    .0,
294            ) << 1u32);
295        let exp2 = tmp2.get_exponent();
296        let tmp1 = tmp2
297            - Float::ln_2_prec(working_prec)
298                .0
299                .mul_prec(Float::from(m), working_prec)
300                .0;
301        if let (Some(exp1), Some(exp2)) = (tmp1.get_exponent(), exp2) {
302            let cancel = u64::saturating_from(exp2 - exp1);
303            // we have 7 ulps of error from the above roundings, 4 ulps from the 4 / s ^ 2 second
304            // order term, plus the canceled bits
305            if float_can_round(
306                tmp1.significand_ref().unwrap(),
307                working_prec.saturating_sub(cancel).saturating_sub(4),
308                prec,
309                rm,
310            ) {
311                return Float::from_float_prec_round(tmp1, prec, rm);
312            }
313            working_prec += cancel + working_prec.ceiling_log_base_2();
314        } else {
315            working_prec += working_prec.ceiling_log_base_2();
316        }
317        working_prec += increment;
318        increment = working_prec >> 1;
319    }
320}
321
322// Computes `ln(1 + eps)` for a nonzero `Rational` `eps` of tiny magnitude (the caller guards `|eps|
323// < 2^(MIN_EXPONENT + 5)`), where the result can lie below the smallest positive `Float`: the
324// bracketing in `ln_rational_helper` could never resolve such a value (its `Float` approximations
325// of `1 + eps` collapse to 1). The Taylor series `ln(1 + eps) = eps - eps^2/2 + eps^3/3 - ...` is
326// summed term by term in exact `Rational`s, bracketing the exact value between two rationals
327// (consecutive partial sums for `eps > 0`, a partial sum and a remainder bound for `eps < 0`) until
328// both ends round to the same `Float`; `from_rational_prec_round` performs the final, possibly
329// underflowing, clamp. Termination: `ln(1 + eps)` is irrational, so some finite bracket eventually
330// separates it from every representable point and tie. This mirrors `exp_rational_near_one`.
331fn ln_rational_near_one(eps: &Rational, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
332    let negative = *eps < 0u32;
333    let mut pow = eps.clone(); // eps^k
334    let mut s = eps.clone(); // S_1
335    let mut k = 1u64;
336    loop {
337        pow *= eps;
338        k += 1;
339        let mut term = &pow / Rational::from(k); // |term| when k even, term when k odd
340        if k.even() {
341            term.neg_assign();
342        }
343        let s_next = &s + &term; // S_k
344        let (lo, hi) = if negative {
345            // Every term is negative, so the partial sums decrease toward ln(1 + eps), and the
346            // remainder after S_k is bounded in magnitude by |eps|^(k+1) / ((k + 1) (1 - |eps|)).
347            let bound = (&pow * eps) / (Rational::from(k + 1) * (Rational::ONE + eps.clone()));
348            // pow * eps = eps^(k+1) is negative here (odd power of a negative number) when k is
349            // even... its sign alternates; take the magnitude explicitly.
350            let bound = -bound.abs();
351            (&s_next + bound, s_next.clone())
352        } else {
353            // The terms alternate in sign with strictly decreasing magnitude, so ln(1 + eps) lies
354            // between consecutive partial sums.
355            if s < s_next {
356                (s.clone(), s_next.clone())
357            } else {
358                (s_next.clone(), s.clone())
359            }
360        };
361        s = s_next;
362        let (f_lo, mut o_lo) = Float::from_rational_prec_round_ref(&lo, prec, rm);
363        let (f_hi, mut o_hi) = Float::from_rational_prec_round_ref(&hi, prec, rm);
364        // A bound that is exactly representable rounds with `Equal`; the exact value lies strictly
365        // inside the bracket, so treat it as agreeing with the other bound.
366        if o_lo == Equal {
367            o_lo = o_hi;
368        }
369        if o_hi == Equal {
370            o_hi = o_lo;
371        }
372        if o_lo == o_hi && f_lo == f_hi {
373            return (f_lo, o_lo);
374        }
375    }
376}
377
378fn ln_rational_helper(x: &Rational, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
379    let mut working_prec = prec + 10;
380    let mut increment = Limb::WIDTH;
381    loop {
382        let (x_lo, x_o) = Float::from_rational_prec_round_ref(x, working_prec, Floor);
383        if x_o == Equal {
384            return ln_prec_round_normal(x_lo, prec, rm);
385        }
386        let (x_lo, x_hi) = floor_and_ceiling((x_lo, x_o));
387        let (ln_lo, mut o_lo) = ln_prec_round_normal(x_lo, prec, rm);
388        let (ln_hi, mut o_hi) = ln_prec_round_normal(x_hi, prec, rm);
389        if o_lo == Equal {
390            o_lo = o_hi;
391        }
392        if o_hi == Equal {
393            o_hi = o_lo;
394        }
395        if o_lo == o_hi && ln_lo == ln_hi {
396            return (ln_lo, o_lo);
397        }
398        working_prec += increment;
399        increment = working_prec >> 1;
400    }
401}
402
403fn ln_rational_helper_extended(x: &Rational, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
404    let mut working_prec = prec + 10;
405    let mut increment = Limb::WIDTH;
406    loop {
407        let (x_lo, x_o) = ExtendedFloat::from_rational_prec_round_ref(x, working_prec, Floor);
408        if x_o == Equal {
409            return ln_prec_round_normal_extended(x_lo, prec, rm);
410        }
411        let (x_lo, x_hi) = crate::float::basic::extended::floor_and_ceiling((x_lo, x_o));
412        let (ln_lo, mut o_lo) = ln_prec_round_normal_extended(x_lo, prec, rm);
413        let (ln_hi, mut o_hi) = ln_prec_round_normal_extended(x_hi, prec, rm);
414        if o_lo == Equal {
415            o_lo = o_hi;
416        }
417        if o_hi == Equal {
418            o_hi = o_lo;
419        }
420        if o_lo == o_hi && ln_lo == ln_hi {
421            return (ln_lo, o_lo);
422        }
423        working_prec += increment;
424        increment = working_prec >> 1;
425    }
426}
427
428// This is the recursive function S from log_ui.c, MPFR 4.2.2. It performs the binary splitting of
429// the Taylor series of log(1 + x) for x = p/2^k, over the terms n1..n2: the sum is T[0]/(B[0] *
430// 2^q). `p`, `b`, and `t` are per-recursion-depth scratch stacks (indexed by depth); `p_val` is odd
431// or zero.
432#[allow(clippy::too_many_arguments)]
433fn log_ui_s(
434    p: &mut [Integer],
435    b: &mut [Integer],
436    t: &mut [Integer],
437    q: &mut u64,
438    n1: u64,
439    n2: u64,
440    p_val: i64,
441    k: u64,
442    need_p: bool,
443) {
444    if n2 == n1 + 1 {
445        p[0] = Integer::from(if n1 == 1 { p_val } else { -p_val });
446        *q = k;
447        b[0] = Integer::from(n1);
448        // T = B * Q * S where S = P / (B * Q), thus T = P
449        t[0] = p[0].clone();
450    } else {
451        // m = floor((n1 + n2) / 2)
452        let m = (n1 >> 1) + (n2 >> 1) + (n1 & n2 & 1);
453        log_ui_s(p, b, t, q, n1, m, p_val, k, true);
454        let mut q1 = 0;
455        let (p_head, p_tail) = p.split_first_mut().unwrap();
456        let (b_head, b_tail) = b.split_first_mut().unwrap();
457        let (t_head, t_tail) = t.split_first_mut().unwrap();
458        log_ui_s(p_tail, b_tail, t_tail, &mut q1, m, n2, p_val, k, need_p);
459        // T[0] <- T[0] * B[1] * 2^q1 + P[0] * B[0] * T[1]
460        t_tail[0] *= &*p_head * &*b_head;
461        *t_head = (&t_tail[0]).add_mul_shl(&*t_head, &b_tail[0], q1);
462        if need_p {
463            *p_head *= &p_tail[0];
464        }
465        *q += q1;
466        *b_head *= &b_tail[0];
467    }
468}
469
470// This is mpfr_log_ui from log_ui.c, MPFR 4.2.2, for n >= 3.
471fn ln_unsigned_prec_round_normal(n: u64, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
472    assert_ne!(rm, Exact, "Inexact ln");
473    // Argument reduction: compute k such that 2/3 < n/2^k < 4/3, i.e., 2^(k+1) < 3n < 2^(k+2). So k
474    // = sizeinbase(3n, 2) - 2.
475    let three_n = 3u128 * u128::from(n);
476    let k = u64::from(128 - three_n.leading_zeros() - 2);
477    // The reduced argument is (n - 2^k)/2^k. p = n - 2^k satisfies |p| < 2^k/3 < n/2 <= i64::MAX,
478    // so it fits in an i64.
479    let mut p = i64::exact_from(i128::from(n) - i128::power_of_2(k));
480    let mut kk = k;
481    if p != 0 {
482        // replace p/2^kk by (p/2)/2^(kk-1) so that p is odd
483        let zeros = p.trailing_zeros();
484        p >>= zeros;
485        kk -= u64::from(zeros);
486    }
487    let mut w = prec + prec.ceiling_log_base_2() + 10;
488    loop {
489        // We need at most w/log2(2^kk/|p|) = w/(kk - log2|p|) terms for an accuracy of w bits.
490        let abs_p = p.unsigned_abs();
491        let n_terms = if abs_p == 0 {
492            2
493        } else {
494            let log2_abs_p = if abs_p == 1 {
495                0
496            } else {
497                abs_p.ceiling_log_base_2()
498            };
499            w.div_ceil(kk - log2_abs_p).max(2)
500        };
501        // The binary-splitting integers T[0] and B[0] * 2^q0 have about n_terms * (log2(n_terms) +
502        // kk) bits; if that exceeds the Float exponent range, converting them to Floats would
503        // overflow to Infinity. In that extreme-precision regime, fall back to the
504        // arithmetic-geometric-mean logarithm, which is correct at any precision and produces the
505        // same correctly-rounded result.
506        let integer_bits = n_terms.saturating_mul(n_terms.ceiling_log_base_2().saturating_add(kk));
507        if integer_bits.saturating_add(64) >= Float::MAX_EXPONENT_U64 {
508            return Float::from(n).ln_prec_round(prec, rm);
509        }
510        let lg_n = usize::exact_from(n_terms.ceiling_log_base_2() + 1);
511        let mut scratch = vec![Integer::ZERO; lg_n * 3];
512        split_into_chunks_mut!(scratch, lg_n, [p_arr, b_arr], t_arr);
513        let mut q0 = 0;
514        log_ui_s(p_arr, b_arr, t_arr, &mut q0, 1, n_terms, p, kk, false);
515        // t = T[0] / (B[0] * 2^q0) = log(n/2^k) approximately
516        let t_num = Float::from_integer_prec(take(&mut t_arr[0]), w).0;
517        let t_den = Float::from_integer_prec(take(&mut b_arr[0]), w).0 << q0;
518        // argument reconstruction: add k * log(2)
519        let t = t_num / t_den + Float::ln_2_prec(w).0 * Float::from_unsigned_prec(k, w).0;
520        // The maximal error is at most k + 6 ulps.
521        let err = (k + 6).ceiling_log_base_2() + 1;
522        if float_can_round(
523            t.significand_ref().unwrap(),
524            w.saturating_sub(err),
525            prec,
526            rm,
527        ) {
528            return Float::from_float_prec_round(t, prec, rm);
529        }
530        w += w >> 1;
531    }
532}
533
534impl Float {
535    /// Computes the natural logarithm of a [`Float`], rounding the result to the specified
536    /// precision and with the specified rounding mode. The [`Float`] is taken by value. An
537    /// [`Ordering`] is also returned, indicating whether the rounded logarithm is less than, equal
538    /// to, or greater than the exact logarithm. Although `NaN`s are not comparable to any
539    /// [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
540    ///
541    /// The logarithm of any nonzero negative number is `NaN`.
542    ///
543    /// See [`RoundingMode`] for a description of the possible rounding modes.
544    ///
545    /// $$
546    /// f(x,p,m) = \ln{x}+\varepsilon.
547    /// $$
548    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
549    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
550    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p+1}$.
551    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
552    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p}$.
553    ///
554    /// If the output has a precision, it is `prec`.
555    ///
556    /// Special cases:
557    /// - $f(\text{NaN},p,m)=\text{NaN}$
558    /// - $f(\infty,p,m)=\infty$
559    /// - $f(-\infty,p,m)=\text{NaN}$
560    /// - $f(\pm0.0,p,m)=-\infty$
561    ///
562    /// Neither overflow nor underflow is possible.
563    ///
564    /// If you know you'll be using `Nearest`, consider using [`Float::ln_prec`] instead. If you
565    /// know that your target precision is the precision of the input, consider using
566    /// [`Float::ln_round`] instead. If both of these things are true, consider using [`Float::ln`]
567    /// instead.
568    ///
569    /// # Worst-case complexity
570    /// $T(n, m) = O(n (\log n)^2 \log\log n + m)$
571    ///
572    /// $M(n, m) = O(n \log n + m)$
573    ///
574    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
575    /// `self.significant_bits()`.
576    ///
577    /// # Panics
578    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the given
579    /// precision.
580    ///
581    /// # Examples
582    /// ```
583    /// use malachite_base::rounding_modes::RoundingMode::*;
584    /// use malachite_float::Float;
585    /// use std::cmp::Ordering::*;
586    ///
587    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
588    ///     .0
589    ///     .ln_prec_round(5, Floor);
590    /// assert_eq!(ln.to_string(), "2.25");
591    /// assert_eq!(o, Less);
592    ///
593    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
594    ///     .0
595    ///     .ln_prec_round(5, Ceiling);
596    /// assert_eq!(ln.to_string(), "2.38");
597    /// assert_eq!(o, Greater);
598    ///
599    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
600    ///     .0
601    ///     .ln_prec_round(5, Nearest);
602    /// assert_eq!(ln.to_string(), "2.25");
603    /// assert_eq!(o, Less);
604    ///
605    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
606    ///     .0
607    ///     .ln_prec_round(20, Floor);
608    /// assert_eq!(ln.to_string(), "2.3025818");
609    /// assert_eq!(o, Less);
610    ///
611    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
612    ///     .0
613    ///     .ln_prec_round(20, Ceiling);
614    /// assert_eq!(ln.to_string(), "2.3025856");
615    /// assert_eq!(o, Greater);
616    ///
617    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
618    ///     .0
619    ///     .ln_prec_round(20, Nearest);
620    /// assert_eq!(ln.to_string(), "2.3025856");
621    /// assert_eq!(o, Greater);
622    /// ```
623    #[inline]
624    pub fn ln_prec_round(self, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
625        assert_ne!(prec, 0);
626        match self {
627            Self(NaN | Infinity { sign: false } | Finite { sign: false, .. }) => {
628                (float_nan!(), Equal)
629            }
630            float_either_zero!() => (float_negative_infinity!(), Equal),
631            float_infinity!() => (float_infinity!(), Equal),
632            _ => ln_prec_round_normal(self, prec, rm),
633        }
634    }
635
636    /// Computes the natural logarithm of a [`Float`], rounding the result to the specified
637    /// precision and with the specified rounding mode. The [`Float`] is taken by reference. An
638    /// [`Ordering`] is also returned, indicating whether the rounded logarithm is less than, equal
639    /// to, or greater than the exact logarithm. Although `NaN`s are not comparable to any
640    /// [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
641    ///
642    /// The logarithm of any nonzero negative number is `NaN`.
643    ///
644    /// See [`RoundingMode`] for a description of the possible rounding modes.
645    ///
646    /// $$
647    /// f(x,p,m) = \ln{x}+\varepsilon.
648    /// $$
649    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
650    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
651    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p+1}$.
652    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
653    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p}$.
654    ///
655    /// If the output has a precision, it is `prec`.
656    ///
657    /// Special cases:
658    /// - $f(\text{NaN},p,m)=\text{NaN}$
659    /// - $f(\infty,p,m)=\infty$
660    /// - $f(-\infty,p,m)=\text{NaN}$
661    /// - $f(\pm0.0,p,m)=-\infty$
662    ///
663    /// Neither overflow nor underflow is possible.
664    ///
665    /// If you know you'll be using `Nearest`, consider using [`Float::ln_prec_ref`] instead. If you
666    /// know that your target precision is the precision of the input, consider using
667    /// [`Float::ln_round_ref`] instead. If both of these things are true, consider using
668    /// `(&Float).ln()`instead.
669    ///
670    /// # Worst-case complexity
671    /// $T(n, m) = O(n (\log n)^2 \log\log n + m)$
672    ///
673    /// $M(n, m) = O(n \log n + m)$
674    ///
675    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
676    /// `self.significant_bits()`.
677    ///
678    /// # Panics
679    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the given
680    /// precision.
681    ///
682    /// # Examples
683    /// ```
684    /// use malachite_base::rounding_modes::RoundingMode::*;
685    /// use malachite_float::Float;
686    /// use std::cmp::Ordering::*;
687    ///
688    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
689    ///     .0
690    ///     .ln_prec_round_ref(5, Floor);
691    /// assert_eq!(ln.to_string(), "2.25");
692    /// assert_eq!(o, Less);
693    ///
694    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
695    ///     .0
696    ///     .ln_prec_round_ref(5, Ceiling);
697    /// assert_eq!(ln.to_string(), "2.38");
698    /// assert_eq!(o, Greater);
699    ///
700    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
701    ///     .0
702    ///     .ln_prec_round_ref(5, Nearest);
703    /// assert_eq!(ln.to_string(), "2.25");
704    /// assert_eq!(o, Less);
705    ///
706    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
707    ///     .0
708    ///     .ln_prec_round_ref(20, Floor);
709    /// assert_eq!(ln.to_string(), "2.3025818");
710    /// assert_eq!(o, Less);
711    ///
712    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
713    ///     .0
714    ///     .ln_prec_round_ref(20, Ceiling);
715    /// assert_eq!(ln.to_string(), "2.3025856");
716    /// assert_eq!(o, Greater);
717    ///
718    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
719    ///     .0
720    ///     .ln_prec_round_ref(20, Nearest);
721    /// assert_eq!(ln.to_string(), "2.3025856");
722    /// assert_eq!(o, Greater);
723    /// ```
724    #[inline]
725    pub fn ln_prec_round_ref(&self, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
726        assert_ne!(prec, 0);
727        match self {
728            Self(NaN | Infinity { sign: false } | Finite { sign: false, .. }) => {
729                (float_nan!(), Equal)
730            }
731            float_either_zero!() => (float_negative_infinity!(), Equal),
732            float_infinity!() => (float_infinity!(), Equal),
733            _ => ln_prec_round_normal_ref(self, prec, rm),
734        }
735    }
736
737    /// Computes the natural logarithm of a [`Float`], rounding the result to the nearest value of
738    /// the specified precision. The [`Float`] is taken by value. An [`Ordering`] is also returned,
739    /// indicating whether the rounded logarithm is less than, equal to, or greater than the exact
740    /// logarithm. Although `NaN`s are not comparable to any [`Float`], whenever this function
741    /// returns a `NaN` it also returns `Equal`.
742    ///
743    /// The logarithm of any nonzero negative number is `NaN`.
744    ///
745    /// If the logarithm is equidistant from two [`Float`]s with the specified precision, the
746    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
747    /// description of the `Nearest` rounding mode.
748    ///
749    /// $$
750    /// f(x,p) = \ln{x}+\varepsilon.
751    /// $$
752    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
753    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
754    ///   \ln{x}\rfloor-p}$.
755    ///
756    /// If the output has a precision, it is `prec`.
757    ///
758    /// Special cases:
759    /// - $f(\text{NaN},p,m)=\text{NaN}$
760    /// - $f(\infty,p,m)=\infty$
761    /// - $f(-\infty,p,m)=\text{NaN}$
762    /// - $f(\pm0.0,p,m)=-\infty$
763    ///
764    /// Neither overflow nor underflow is possible.
765    ///
766    /// If you want to use a rounding mode other than `Nearest`, consider using
767    /// [`Float::ln_prec_round`] instead. If you know that your target precision is the precision of
768    /// the input, consider using [`Float::ln`] instead.
769    ///
770    /// # Worst-case complexity
771    /// $T(n, m) = O(n (\log n)^2 \log\log n + m)$
772    ///
773    /// $M(n, m) = O(n \log n + m)$
774    ///
775    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
776    /// `self.significant_bits()`.
777    ///
778    /// # Examples
779    /// ```
780    /// use malachite_float::Float;
781    /// use std::cmp::Ordering::*;
782    ///
783    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_prec(5);
784    /// assert_eq!(ln.to_string(), "2.25");
785    /// assert_eq!(o, Less);
786    ///
787    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_prec(20);
788    /// assert_eq!(ln.to_string(), "2.3025856");
789    /// assert_eq!(o, Greater);
790    /// ```
791    #[inline]
792    pub fn ln_prec(self, prec: u64) -> (Self, Ordering) {
793        self.ln_prec_round(prec, Nearest)
794    }
795
796    /// Computes the natural logarithm of a [`Float`], rounding the result to the nearest value of
797    /// the specified precision. The [`Float`] is taken by reference. An [`Ordering`] is also
798    /// returned, indicating whether the rounded logarithm is less than, equal to, or greater than
799    /// the exact logarithm. Although `NaN`s are not comparable to any [`Float`], whenever this
800    /// function returns a `NaN` it also returns `Equal`.
801    ///
802    /// The logarithm of any nonzero negative number is `NaN`.
803    ///
804    /// If the logarithm is equidistant from two [`Float`]s with the specified precision, the
805    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
806    /// description of the `Nearest` rounding mode.
807    ///
808    /// $$
809    /// f(x,p) = \ln{x}+\varepsilon.
810    /// $$
811    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
812    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
813    ///   \ln{x}\rfloor-p}$.
814    ///
815    /// If the output has a precision, it is `prec`.
816    ///
817    /// Special cases:
818    /// - $f(\text{NaN},p)=\text{NaN}$
819    /// - $f(\infty,p)=\infty$
820    /// - $f(-\infty,p)=\text{NaN}$
821    /// - $f(\pm0.0,p)=-\infty$
822    ///
823    /// Neither overflow nor underflow is possible.
824    ///
825    /// If you want to use a rounding mode other than `Nearest`, consider using
826    /// [`Float::ln_prec_round_ref`] instead. If you know that your target precision is the
827    /// precision of the input, consider using `(&Float).ln()` instead.
828    ///
829    /// # Worst-case complexity
830    /// $T(n, m) = O(n (\log n)^2 \log\log n + m)$
831    ///
832    /// $M(n, m) = O(n \log n + m)$
833    ///
834    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
835    /// `self.significant_bits()`.
836    ///
837    /// # Examples
838    /// ```
839    /// use malachite_float::Float;
840    /// use std::cmp::Ordering::*;
841    ///
842    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_prec_ref(5);
843    /// assert_eq!(ln.to_string(), "2.25");
844    /// assert_eq!(o, Less);
845    ///
846    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_prec_ref(20);
847    /// assert_eq!(ln.to_string(), "2.3025856");
848    /// assert_eq!(o, Greater);
849    /// ```
850    #[inline]
851    pub fn ln_prec_ref(&self, prec: u64) -> (Self, Ordering) {
852        self.ln_prec_round_ref(prec, Nearest)
853    }
854
855    /// Computes the natural logarithm of a [`Float`], rounding the result with the specified
856    /// rounding mode. The [`Float`] is taken by value. An [`Ordering`] is also returned, indicating
857    /// whether the rounded logarithm is less than, equal to, or greater than the exact logarithm.
858    /// Although `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN`
859    /// it also returns `Equal`.
860    ///
861    /// The logarithm of any nonzero negative number is `NaN`.
862    ///
863    /// The precision of the output is the precision of the input. See [`RoundingMode`] for a
864    /// description of the possible rounding modes.
865    ///
866    /// $$
867    /// f(x,m) = \ln{x}+\varepsilon.
868    /// $$
869    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
870    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
871    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p+1}$, where $p$ is the precision of the input.
872    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
873    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p}$, where $p$ is the precision of the input.
874    ///
875    /// If the output has a precision, it is the precision of the input.
876    ///
877    /// Special cases:
878    /// - $f(\text{NaN},m)=\text{NaN}$
879    /// - $f(\infty,m)=\infty$
880    /// - $f(-\infty,m)=\text{NaN}$
881    /// - $f(\pm0.0,m)=-\infty$
882    ///
883    /// Neither overflow nor underflow is possible.
884    ///
885    /// If you want to specify an output precision, consider using [`Float::ln_prec_round`] instead.
886    /// If you know you'll be using the `Nearest` rounding mode, consider using [`Float::ln`]
887    /// instead.
888    ///
889    /// # Worst-case complexity
890    /// $T(n) = O(n (\log n)^2 \log\log n)$
891    ///
892    /// $M(n) = O(n \log n)$
893    ///
894    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.get_prec()`.
895    ///
896    /// # Panics
897    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the input
898    /// precision.
899    ///
900    /// # Examples
901    /// ```
902    /// use malachite_base::rounding_modes::RoundingMode::*;
903    /// use malachite_float::Float;
904    /// use std::cmp::Ordering::*;
905    ///
906    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_round(Floor);
907    /// assert_eq!(ln.to_string(), "2.3025850929940456840179914546838");
908    /// assert_eq!(o, Less);
909    ///
910    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_round(Ceiling);
911    /// assert_eq!(ln.to_string(), "2.3025850929940456840179914546870");
912    /// assert_eq!(o, Greater);
913    ///
914    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_round(Nearest);
915    /// assert_eq!(ln.to_string(), "2.3025850929940456840179914546838");
916    /// assert_eq!(o, Less);
917    /// ```
918    #[inline]
919    pub fn ln_round(self, rm: RoundingMode) -> (Self, Ordering) {
920        let prec = self.significant_bits();
921        self.ln_prec_round(prec, rm)
922    }
923
924    /// Computes the natural logarithm of a [`Float`], rounding the result with the specified
925    /// rounding mode. The [`Float`] is taken by reference. An [`Ordering`] is also returned,
926    /// indicating whether the rounded logarithm is less than, equal to, or greater than the exact
927    /// logarithm. Although `NaN`s are not comparable to any [`Float`], whenever this function
928    /// returns a `NaN` it also returns `Equal`.
929    ///
930    /// The logarithm of any nonzero negative number is `NaN`.
931    ///
932    /// The precision of the output is the precision of the input. See [`RoundingMode`] for a
933    /// description of the possible rounding modes.
934    ///
935    /// $$
936    /// f(x,m) = \ln{x}+\varepsilon.
937    /// $$
938    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
939    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
940    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p+1}$, where $p$ is the precision of the input.
941    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
942    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p}$, where $p$ is the precision of the input.
943    ///
944    /// If the output has a precision, it is the precision of the input.
945    ///
946    /// Special cases:
947    /// - $f(\text{NaN},m)=\text{NaN}$
948    /// - $f(\infty,m)=\infty$
949    /// - $f(-\infty,m)=\text{NaN}$
950    /// - $f(\pm0.0,m)=-\infty$
951    ///
952    /// Neither overflow nor underflow is possible.
953    ///
954    /// If you want to specify an output precision, consider using [`Float::ln_prec_round_ref`]
955    /// instead. If you know you'll be using the `Nearest` rounding mode, consider using
956    /// `(&Float).ln()` instead.
957    ///
958    /// # Worst-case complexity
959    /// $T(n) = O(n (\log n)^2 \log\log n)$
960    ///
961    /// $M(n) = O(n \log n)$
962    ///
963    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.get_prec()`.
964    ///
965    /// # Panics
966    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the input
967    /// precision.
968    ///
969    /// # Examples
970    /// ```
971    /// use malachite_base::rounding_modes::RoundingMode::*;
972    /// use malachite_float::Float;
973    /// use std::cmp::Ordering::*;
974    ///
975    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_round_ref(Floor);
976    /// assert_eq!(ln.to_string(), "2.3025850929940456840179914546838");
977    /// assert_eq!(o, Less);
978    ///
979    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
980    ///     .0
981    ///     .ln_round_ref(Ceiling);
982    /// assert_eq!(ln.to_string(), "2.3025850929940456840179914546870");
983    /// assert_eq!(o, Greater);
984    ///
985    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
986    ///     .0
987    ///     .ln_round_ref(Nearest);
988    /// assert_eq!(ln.to_string(), "2.3025850929940456840179914546838");
989    /// assert_eq!(o, Less);
990    /// ```
991    #[inline]
992    pub fn ln_round_ref(&self, rm: RoundingMode) -> (Self, Ordering) {
993        let prec = self.significant_bits();
994        self.ln_prec_round_ref(prec, rm)
995    }
996
997    /// Computes the natural logarithm of a [`Float`] in place, rounding the result to the specified
998    /// precision and with the specified rounding mode. An [`Ordering`] is returned, indicating
999    /// whether the rounded logarithm is less than, equal to, or greater than the exact logarithm.
1000    /// Although `NaN`s are not comparable to any [`Float`], whenever this function sets the
1001    /// [`Float`] to `NaN` it also returns `Equal`.
1002    ///
1003    /// The logarithm of any nonzero negative number is `NaN`.
1004    ///
1005    /// See [`RoundingMode`] for a description of the possible rounding modes.
1006    ///
1007    /// $$
1008    /// x \gets \ln{x}+\varepsilon.
1009    /// $$
1010    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1011    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
1012    ///   2^{\lfloor\log_2 |xy|\rfloor-p+1}$.
1013    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
1014    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p}$.
1015    ///
1016    /// If the output has a precision, it is `prec`.
1017    ///
1018    /// See the [`Float::ln_prec_round`] documentation for information on special cases, overflow,
1019    /// and underflow.
1020    ///
1021    /// If you know you'll be using `Nearest`, consider using [`Float::ln_prec_assign`] instead. If
1022    /// you know that your target precision is the precision of the input, consider using
1023    /// [`Float::ln_round_assign`] instead. If both of these things are true, consider using
1024    /// [`Float::ln_assign`] instead.
1025    ///
1026    /// # Worst-case complexity
1027    /// $T(n, m) = O(n (\log n)^2 \log\log n + m)$
1028    ///
1029    /// $M(n, m) = O(n \log n + m)$
1030    ///
1031    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
1032    /// `self.significant_bits()`.
1033    ///
1034    /// # Panics
1035    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the given
1036    /// precision.
1037    ///
1038    /// # Examples
1039    /// ```
1040    /// use malachite_base::rounding_modes::RoundingMode::*;
1041    /// use malachite_float::Float;
1042    /// use std::cmp::Ordering::*;
1043    ///
1044    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
1045    /// assert_eq!(x.ln_prec_round_assign(5, Floor), Less);
1046    /// assert_eq!(x.to_string(), "2.25");
1047    ///
1048    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
1049    /// assert_eq!(x.ln_prec_round_assign(5, Ceiling), Greater);
1050    /// assert_eq!(x.to_string(), "2.38");
1051    ///
1052    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
1053    /// assert_eq!(x.ln_prec_round_assign(5, Nearest), Less);
1054    /// assert_eq!(x.to_string(), "2.25");
1055    ///
1056    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
1057    /// assert_eq!(x.ln_prec_round_assign(20, Floor), Less);
1058    /// assert_eq!(x.to_string(), "2.3025818");
1059    ///
1060    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
1061    /// assert_eq!(x.ln_prec_round_assign(20, Ceiling), Greater);
1062    /// assert_eq!(x.to_string(), "2.3025856");
1063    ///
1064    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
1065    /// assert_eq!(x.ln_prec_round_assign(20, Nearest), Greater);
1066    /// assert_eq!(x.to_string(), "2.3025856");
1067    /// ```
1068    #[inline]
1069    pub fn ln_prec_round_assign(&mut self, prec: u64, rm: RoundingMode) -> Ordering {
1070        let mut x = Self::ZERO;
1071        swap(self, &mut x);
1072        let o;
1073        (*self, o) = x.ln_prec_round(prec, rm);
1074        o
1075    }
1076
1077    /// Computes the natural logarithm of a [`Float`] in place, rounding the result to the nearest
1078    /// value of the specified precision. An [`Ordering`] is returned, indicating whether the
1079    /// rounded logarithm is less than, equal to, or greater than the exact logarithm. Although
1080    /// `NaN`s are not comparable to any [`Float`], whenever this function sets the [`Float`] to
1081    /// `NaN` it also returns `Equal`.
1082    ///
1083    /// The logarithm of any nonzero negative number is `NaN`.
1084    ///
1085    /// If the logarithm is equidistant from two [`Float`]s with the specified precision, the
1086    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
1087    /// description of the `Nearest` rounding mode.
1088    ///
1089    /// $$
1090    /// x \gets \ln{x}+\varepsilon.
1091    /// $$
1092    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1093    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
1094    ///   \ln{x}\rfloor-p}$.
1095    ///
1096    /// If the output has a precision, it is `prec`.
1097    ///
1098    /// See the [`Float::ln_prec`] documentation for information on special cases, overflow, and
1099    /// underflow.
1100    ///
1101    /// If you want to use a rounding mode other than `Nearest`, consider using
1102    /// [`Float::ln_prec_round_assign`] instead. If you know that your target precision is the
1103    /// precision of the input, consider using [`Float::ln`] instead.
1104    ///
1105    /// # Worst-case complexity
1106    /// $T(n, m) = O(n (\log n)^2 \log\log n + m)$
1107    ///
1108    /// $M(n, m) = O(n \log n + m)$
1109    ///
1110    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
1111    /// `self.significant_bits()`.
1112    ///
1113    /// # Examples
1114    /// ```
1115    /// use malachite_float::Float;
1116    /// use std::cmp::Ordering::*;
1117    ///
1118    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
1119    /// assert_eq!(x.ln_prec_assign(5), Less);
1120    /// assert_eq!(x.to_string(), "2.25");
1121    ///
1122    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
1123    /// assert_eq!(x.ln_prec_assign(20), Greater);
1124    /// assert_eq!(x.to_string(), "2.3025856");
1125    /// ```
1126    #[inline]
1127    pub fn ln_prec_assign(&mut self, prec: u64) -> Ordering {
1128        self.ln_prec_round_assign(prec, Nearest)
1129    }
1130
1131    /// Computes the natural logarithm of a [`Float`] in place, rounding the result with the
1132    /// specified rounding mode. An [`Ordering`] is returned, indicating whether the rounded
1133    /// logarithm is less than, equal to, or greater than the exact logarithm. Although `NaN`s are
1134    /// not comparable to any [`Float`], whenever this function sets the [`Float`] to `NaN` it also
1135    /// returns `Equal`.
1136    ///
1137    /// The logarithm of any nonzero negative number is `NaN`.
1138    ///
1139    /// The precision of the output is the precision of the input. See [`RoundingMode`] for a
1140    /// description of the possible rounding modes.
1141    ///
1142    /// $$
1143    /// x \gets \ln{x}+\varepsilon.
1144    /// $$
1145    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1146    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
1147    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p+1}$, where $p$ is the maximum precision of the inputs.
1148    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
1149    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p}$, where $p$ is the maximum precision of the inputs.
1150    ///
1151    /// If the output has a precision, it is the precision of the input.
1152    ///
1153    /// See the [`Float::ln_round`] documentation for information on special cases, overflow, and
1154    /// underflow.
1155    ///
1156    /// If you want to specify an output precision, consider using [`Float::ln_prec_round_assign`]
1157    /// instead. If you know you'll be using the `Nearest` rounding mode, consider using
1158    /// [`Float::ln_assign`] instead.
1159    ///
1160    /// # Worst-case complexity
1161    /// $T(n) = O(n (\log n)^2 \log\log n)$
1162    ///
1163    /// $M(n) = O(n \log n)$
1164    ///
1165    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.get_prec()`.
1166    ///
1167    /// # Panics
1168    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the input
1169    /// precision.
1170    ///
1171    /// # Examples
1172    /// ```
1173    /// use malachite_base::rounding_modes::RoundingMode::*;
1174    /// use malachite_float::Float;
1175    /// use std::cmp::Ordering::*;
1176    ///
1177    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
1178    /// assert_eq!(x.ln_round_assign(Floor), Less);
1179    /// assert_eq!(x.to_string(), "2.3025850929940456840179914546838");
1180    ///
1181    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
1182    /// assert_eq!(x.ln_round_assign(Ceiling), Greater);
1183    /// assert_eq!(x.to_string(), "2.3025850929940456840179914546870");
1184    ///
1185    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
1186    /// assert_eq!(x.ln_round_assign(Nearest), Less);
1187    /// assert_eq!(x.to_string(), "2.3025850929940456840179914546838");
1188    /// ```
1189    #[inline]
1190    pub fn ln_round_assign(&mut self, rm: RoundingMode) -> Ordering {
1191        let prec = self.significant_bits();
1192        self.ln_prec_round_assign(prec, rm)
1193    }
1194
1195    /// Computes the natural logarithm of a [`Rational`], rounding the result to the specified
1196    /// precision and with the specified rounding mode and returning the result as a [`Float`]. The
1197    /// [`Rational`] is taken by value. An [`Ordering`] is also returned, indicating whether the
1198    /// rounded logarithm is less than, equal to, or greater than the exact logarithm. Although
1199    /// `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN` it also
1200    /// returns `Equal`.
1201    ///
1202    /// The logarithm of any nonzero negative number is `NaN`.
1203    ///
1204    /// See [`RoundingMode`] for a description of the possible rounding modes.
1205    ///
1206    /// $$
1207    /// f(x,p,m) = \ln{x}+\varepsilon.
1208    /// $$
1209    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1210    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
1211    ///   2^{\lfloor\log_2 |\ln{x}|\rfloor-p+1}$.
1212    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
1213    ///   2^{\lfloor\log_2 |\ln{x}|\rfloor-p}$.
1214    ///
1215    /// If the output has a precision, it is `prec`.
1216    ///
1217    /// Special cases:
1218    /// - $f(0.0,p,m)=-\infty$
1219    ///
1220    /// Neither overflow nor underflow is possible.
1221    ///
1222    /// If you know you'll be using `Nearest`, consider using [`Float::ln_rational_prec`] instead.
1223    ///
1224    /// # Worst-case complexity
1225    /// $T(n, m) = O(n (\log n)^2 \log\log n + m)$
1226    ///
1227    /// $M(n, m) = O(n \log n + m)$
1228    ///
1229    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
1230    /// `x.significant_bits()`.
1231    ///
1232    /// # Panics
1233    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the given
1234    /// precision.
1235    ///
1236    /// # Examples
1237    /// ```
1238    /// use malachite_base::rounding_modes::RoundingMode::*;
1239    /// use malachite_float::Float;
1240    /// use malachite_q::Rational;
1241    /// use std::cmp::Ordering::*;
1242    ///
1243    /// let (ln, o) = Float::ln_rational_prec_round(Rational::from_unsigneds(3u8, 5), 5, Floor);
1244    /// assert_eq!(ln.to_string(), "-0.531");
1245    /// assert_eq!(o, Less);
1246    ///
1247    /// let (ln, o) = Float::ln_rational_prec_round(Rational::from_unsigneds(3u8, 5), 5, Ceiling);
1248    /// assert_eq!(ln.to_string(), "-0.500");
1249    /// assert_eq!(o, Greater);
1250    ///
1251    /// let (ln, o) = Float::ln_rational_prec_round(Rational::from_unsigneds(3u8, 5), 5, Nearest);
1252    /// assert_eq!(ln.to_string(), "-0.500");
1253    /// assert_eq!(o, Greater);
1254    ///
1255    /// let (ln, o) = Float::ln_rational_prec_round(Rational::from_unsigneds(3u8, 5), 20, Floor);
1256    /// assert_eq!(ln.to_string(), "-0.51082611");
1257    /// assert_eq!(o, Less);
1258    ///
1259    /// let (ln, o) = Float::ln_rational_prec_round(Rational::from_unsigneds(3u8, 5), 20, Ceiling);
1260    /// assert_eq!(ln.to_string(), "-0.51082516");
1261    /// assert_eq!(o, Greater);
1262    ///
1263    /// let (ln, o) = Float::ln_rational_prec_round(Rational::from_unsigneds(3u8, 5), 20, Nearest);
1264    /// assert_eq!(ln.to_string(), "-0.51082516");
1265    /// assert_eq!(o, Greater);
1266    /// ```
1267    #[allow(clippy::needless_pass_by_value)]
1268    #[inline]
1269    pub fn ln_rational_prec_round(x: Rational, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
1270        Self::ln_rational_prec_round_ref(&x, prec, rm)
1271    }
1272
1273    /// Computes the natural logarithm of a [`Rational`], rounding the result to the specified
1274    /// precision and with the specified rounding mode and returning the result as a [`Float`]. The
1275    /// [`Rational`] is taken by reference. An [`Ordering`] is also returned, indicating whether the
1276    /// rounded logarithm is less than, equal to, or greater than the exact logarithm. Although
1277    /// `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN` it also
1278    /// returns `Equal`.
1279    ///
1280    /// The logarithm of any nonzero negative number is `NaN`.
1281    ///
1282    /// See [`RoundingMode`] for a description of the possible rounding modes.
1283    ///
1284    /// $$
1285    /// f(x,p,m) = \ln{x}+\varepsilon.
1286    /// $$
1287    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1288    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
1289    ///   2^{\lfloor\log_2 |\ln{x}|\rfloor-p+1}$.
1290    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
1291    ///   2^{\lfloor\log_2 |\ln{x}|\rfloor-p}$.
1292    ///
1293    /// If the output has a precision, it is `prec`.
1294    ///
1295    /// Special cases:
1296    /// - $f(0.0,p,m)=-\infty$
1297    ///
1298    /// Neither overflow nor underflow is possible.
1299    ///
1300    /// If you know you'll be using `Nearest`, consider using [`Float::ln_rational_prec_ref`]
1301    /// instead.
1302    ///
1303    /// # Worst-case complexity
1304    /// $T(n, m) = O(n (\log n)^2 \log\log n + m)$
1305    ///
1306    /// $M(n, m) = O(n \log n + m)$
1307    ///
1308    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
1309    /// `x.significant_bits()`.
1310    ///
1311    /// # Panics
1312    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the given
1313    /// precision.
1314    ///
1315    /// # Examples
1316    /// ```
1317    /// use malachite_base::rounding_modes::RoundingMode::*;
1318    /// use malachite_float::Float;
1319    /// use malachite_q::Rational;
1320    /// use std::cmp::Ordering::*;
1321    ///
1322    /// let (ln, o) =
1323    ///     Float::ln_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 5, Floor);
1324    /// assert_eq!(ln.to_string(), "-0.531");
1325    /// assert_eq!(o, Less);
1326    ///
1327    /// let (ln, o) =
1328    ///     Float::ln_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 5, Ceiling);
1329    /// assert_eq!(ln.to_string(), "-0.500");
1330    /// assert_eq!(o, Greater);
1331    ///
1332    /// let (ln, o) =
1333    ///     Float::ln_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 5, Nearest);
1334    /// assert_eq!(ln.to_string(), "-0.500");
1335    /// assert_eq!(o, Greater);
1336    ///
1337    /// let (ln, o) =
1338    ///     Float::ln_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 20, Floor);
1339    /// assert_eq!(ln.to_string(), "-0.51082611");
1340    /// assert_eq!(o, Less);
1341    ///
1342    /// let (ln, o) =
1343    ///     Float::ln_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 20, Ceiling);
1344    /// assert_eq!(ln.to_string(), "-0.51082516");
1345    /// assert_eq!(o, Greater);
1346    ///
1347    /// let (ln, o) =
1348    ///     Float::ln_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 20, Nearest);
1349    /// assert_eq!(ln.to_string(), "-0.51082516");
1350    /// assert_eq!(o, Greater);
1351    /// ```
1352    pub fn ln_rational_prec_round_ref(
1353        x: &Rational,
1354        prec: u64,
1355        rm: RoundingMode,
1356    ) -> (Self, Ordering) {
1357        assert_ne!(prec, 0);
1358        match x.sign() {
1359            Equal => return (float_negative_infinity!(), Equal),
1360            Less => return (float_nan!(), Equal),
1361            Greater => {}
1362        }
1363        if *x == 1u32 {
1364            return (float_zero!(), Equal);
1365        }
1366        assert_ne!(rm, Exact, "Inexact ln");
1367        // x within a sliver of 1: ln(x) ~ x - 1 may fall below the smallest positive Float, which
1368        // the helpers below could never resolve.
1369        let eps = x - Rational::ONE;
1370        if eps.floor_log_base_2_abs() <= Self::MIN_EXPONENT_PLUS_4_I64 {
1371            return ln_rational_near_one(&eps, prec, rm);
1372        }
1373        let x_exp = i32::saturating_from(x.floor_log_base_2_abs()).saturating_add(1);
1374        if x_exp >= const { Self::MAX_EXPONENT - 1 } || x_exp <= const { Self::MIN_EXPONENT + 1 } {
1375            ln_rational_helper_extended(x, prec, rm)
1376        } else {
1377            ln_rational_helper(x, prec, rm)
1378        }
1379    }
1380
1381    /// Computes the natural logarithm of a [`Rational`], rounding the result to the nearest value
1382    /// of the specified precision and returning the result as a [`Float`]. The [`Rational`] is
1383    /// taken by value. An [`Ordering`] is also returned, indicating whether the rounded logarithm
1384    /// is less than, equal to, or greater than the exact logarithm. Although `NaN`s are not
1385    /// comparable to any [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
1386    ///
1387    /// The logarithm of any nonzero negative number is `NaN`.
1388    ///
1389    /// If the logarithm is equidistant from two [`Float`]s with the specified precision, the
1390    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
1391    /// description of the `Nearest` rounding mode.
1392    ///
1393    /// $$
1394    /// f(x,p) = \ln{x}+\varepsilon.
1395    /// $$
1396    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1397    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
1398    ///   |\ln{x}|\rfloor-p}$.
1399    ///
1400    /// If the output has a precision, it is `prec`.
1401    ///
1402    /// Special cases:
1403    /// - $f(0.0,p)=-\infty$
1404    ///
1405    /// Neither overflow nor underflow is possible.
1406    ///
1407    /// If you want to use a rounding mode other than `Nearest`, consider using
1408    /// [`Float::ln_rational_prec_round`] instead.
1409    ///
1410    /// # Worst-case complexity
1411    /// $T(n, m) = O(n (\log n)^2 \log\log n + m)$
1412    ///
1413    /// $M(n, m) = O(n \log n + m)$
1414    ///
1415    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
1416    /// `x.significant_bits()`.
1417    ///
1418    /// # Examples
1419    /// ```
1420    /// use malachite_float::Float;
1421    /// use malachite_q::Rational;
1422    /// use std::cmp::Ordering::*;
1423    ///
1424    /// let (ln, o) = Float::ln_rational_prec(Rational::from_unsigneds(3u8, 5), 5);
1425    /// assert_eq!(ln.to_string(), "-0.500");
1426    /// assert_eq!(o, Greater);
1427    ///
1428    /// let (ln, o) = Float::ln_rational_prec(Rational::from_unsigneds(3u8, 5), 20);
1429    /// assert_eq!(ln.to_string(), "-0.51082516");
1430    /// assert_eq!(o, Greater);
1431    /// ```
1432    #[inline]
1433    pub fn ln_rational_prec(x: Rational, prec: u64) -> (Self, Ordering) {
1434        Self::ln_rational_prec_round(x, prec, Nearest)
1435    }
1436
1437    /// Computes the natural logarithm of a [`Rational`], rounding the result to the nearest value
1438    /// of the specified precision and returning the result as a [`Float`]. The [`Rational`] is
1439    /// taken by reference. An [`Ordering`] is also returned, indicating whether the rounded
1440    /// logarithm is less than, equal to, or greater than the exact logarithm. Although `NaN`s are
1441    /// not comparable to any [`Float`], whenever this function returns a `NaN` it also returns
1442    /// `Equal`.
1443    ///
1444    /// The logarithm of any nonzero negative number is `NaN`.
1445    ///
1446    /// If the logarithm is equidistant from two [`Float`]s with the specified precision, the
1447    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
1448    /// description of the `Nearest` rounding mode.
1449    ///
1450    /// $$
1451    /// f(x,p) = \ln{x}+\varepsilon.
1452    /// $$
1453    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1454    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
1455    ///   |\ln{x}|\rfloor-p}$.
1456    ///
1457    /// If the output has a precision, it is `prec`.
1458    ///
1459    /// Special cases:
1460    /// - $f(0.0,p)=-\infty$
1461    ///
1462    /// Neither overflow nor underflow is possible.
1463    ///
1464    /// If you want to use a rounding mode other than `Nearest`, consider using
1465    /// [`Float::ln_rational_prec_round_ref`] instead.
1466    ///
1467    /// # Worst-case complexity
1468    /// $T(n, m) = O(n (\log n)^2 \log\log n + m)$
1469    ///
1470    /// $M(n, m) = O(n \log n + m)$
1471    ///
1472    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
1473    /// `x.significant_bits()`.
1474    ///
1475    /// # Examples
1476    /// ```
1477    /// use malachite_float::Float;
1478    /// use malachite_q::Rational;
1479    /// use std::cmp::Ordering::*;
1480    ///
1481    /// let (ln, o) = Float::ln_rational_prec_ref(&Rational::from_unsigneds(3u8, 5), 5);
1482    /// assert_eq!(ln.to_string(), "-0.500");
1483    /// assert_eq!(o, Greater);
1484    ///
1485    /// let (ln, o) = Float::ln_rational_prec_ref(&Rational::from_unsigneds(3u8, 5), 20);
1486    /// assert_eq!(ln.to_string(), "-0.51082516");
1487    /// assert_eq!(o, Greater);
1488    /// ```
1489    #[inline]
1490    pub fn ln_rational_prec_ref(x: &Rational, prec: u64) -> (Self, Ordering) {
1491        Self::ln_rational_prec_round_ref(x, prec, Nearest)
1492    }
1493
1494    /// Computes the natural logarithm of an unsigned integer, returning a [`Float`]. The result is
1495    /// rounded to the specified precision and with the specified rounding mode. An [`Ordering`] is
1496    /// also returned, indicating whether the rounded logarithm is less than, equal to, or greater
1497    /// than the exact logarithm.
1498    ///
1499    /// This is typically faster than converting the integer to a [`Float`] and taking its
1500    /// logarithm, as it uses binary splitting of the Taylor series of the logarithm rather than the
1501    /// arithmetic-geometric mean iteration.
1502    ///
1503    /// See [`RoundingMode`] for a description of the possible rounding modes.
1504    ///
1505    /// $$
1506    /// f(n,p,m) = \ln{n}+\varepsilon.
1507    /// $$
1508    /// - If $\ln{n}$ is infinite or zero, $\varepsilon$ may be ignored or assumed to be 0.
1509    /// - If $\ln{n}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
1510    ///   2^{\lfloor\log_2 (\ln{n})\rfloor-p+1}$.
1511    /// - If $\ln{n}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
1512    ///   2^{\lfloor\log_2 (\ln{n})\rfloor-p}$.
1513    ///
1514    /// If the output has a precision, it is `prec`.
1515    ///
1516    /// Special cases:
1517    /// - $f(0,p,m)=-\infty$
1518    /// - $f(1,p,m)=0.0$
1519    ///
1520    /// Neither overflow nor underflow is possible.
1521    ///
1522    /// If you know you'll be using `Nearest`, consider using [`Float::ln_unsigned_prec`] instead.
1523    ///
1524    /// # Worst-case complexity
1525    /// $T(n) = O(n (\log n)^2 \log\log n)$
1526    ///
1527    /// $M(n) = O(n \log n)$
1528    ///
1529    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
1530    ///
1531    /// # Panics
1532    /// Panics if `prec` is zero, or if `rm` is `Exact` but the logarithm is irrational (that is,
1533    /// whenever $n \geq 2$).
1534    ///
1535    /// # Examples
1536    /// ```
1537    /// use malachite_base::rounding_modes::RoundingMode::*;
1538    /// use malachite_float::Float;
1539    /// use std::cmp::Ordering::*;
1540    ///
1541    /// let (ln, o) = Float::ln_unsigned_prec_round(10, 100, Floor);
1542    /// assert_eq!(ln.to_string(), "2.3025850929940456840179914546838");
1543    /// assert_eq!(o, Less);
1544    ///
1545    /// let (ln, o) = Float::ln_unsigned_prec_round(10, 100, Ceiling);
1546    /// assert_eq!(ln.to_string(), "2.3025850929940456840179914546870");
1547    /// assert_eq!(o, Greater);
1548    ///
1549    /// let (ln, o) = Float::ln_unsigned_prec_round(1, 10, Exact);
1550    /// assert_eq!(ln.to_string(), "0.0");
1551    /// assert_eq!(o, Equal);
1552    /// ```
1553    ///
1554    /// This is `mpfr_log_ui` from `log_ui.c`, MPFR 4.2.2.
1555    pub fn ln_unsigned_prec_round(n: u64, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
1556        assert_ne!(prec, 0);
1557        match n {
1558            // log(0) is an exact -Infinity
1559            0 => (Self::NEGATIVE_INFINITY, Equal),
1560            // log(1) = 0, the only "normal" case where the result is exact
1561            1 => (Self::ZERO, Equal),
1562            2 => Self::ln_2_prec_round(prec, rm),
1563            _ => ln_unsigned_prec_round_normal(n, prec, rm),
1564        }
1565    }
1566
1567    /// Computes the natural logarithm of an unsigned integer, returning a [`Float`]. The result is
1568    /// rounded to the specified precision and to the nearest value. An [`Ordering`] is also
1569    /// returned, indicating whether the rounded logarithm is less than, equal to, or greater than
1570    /// the exact logarithm.
1571    ///
1572    /// This is typically faster than converting the integer to a [`Float`] and taking its
1573    /// logarithm, as it uses binary splitting of the Taylor series of the logarithm rather than the
1574    /// arithmetic-geometric mean iteration.
1575    ///
1576    /// If the logarithm is equidistant from two [`Float`]s with the specified precision, the
1577    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
1578    /// description of the `Nearest` rounding mode.
1579    ///
1580    /// $$
1581    /// f(n,p) = \ln{n}+\varepsilon.
1582    /// $$
1583    /// - If $\ln{n}$ is infinite or zero, $\varepsilon$ may be ignored or assumed to be 0.
1584    /// - If $\ln{n}$ is finite and nonzero, then $|\varepsilon| \leq 2^{\lfloor\log_2
1585    ///   (\ln{n})\rfloor-p}$.
1586    ///
1587    /// If the output has a precision, it is `prec`.
1588    ///
1589    /// Special cases:
1590    /// - $f(0,p)=-\infty$
1591    /// - $f(1,p)=0.0$
1592    ///
1593    /// Neither overflow nor underflow is possible.
1594    ///
1595    /// If you want to specify a rounding mode as well, consider using
1596    /// [`Float::ln_unsigned_prec_round`] instead.
1597    ///
1598    /// # Worst-case complexity
1599    /// $T(n) = O(n (\log n)^2 \log\log n)$
1600    ///
1601    /// $M(n) = O(n \log n)$
1602    ///
1603    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
1604    ///
1605    /// # Panics
1606    /// Panics if `prec` is zero.
1607    ///
1608    /// # Examples
1609    /// ```
1610    /// use malachite_float::Float;
1611    /// use std::cmp::Ordering::*;
1612    ///
1613    /// let (ln, o) = Float::ln_unsigned_prec(10, 100);
1614    /// assert_eq!(ln.to_string(), "2.3025850929940456840179914546838");
1615    /// assert_eq!(o, Less);
1616    ///
1617    /// let (ln, o) = Float::ln_unsigned_prec(0, 10);
1618    /// assert_eq!(ln.to_string(), "-Infinity");
1619    /// assert_eq!(o, Equal);
1620    /// ```
1621    #[inline]
1622    pub fn ln_unsigned_prec(n: u64, prec: u64) -> (Self, Ordering) {
1623        Self::ln_unsigned_prec_round(n, prec, Nearest)
1624    }
1625}
1626
1627impl Ln for Float {
1628    type Output = Self;
1629
1630    /// Computes the natural logarithm of a [`Float`], taking it by value.
1631    ///
1632    /// If the output has a precision, it is the precision of the input. If the logarithm is
1633    /// equidistant from two [`Float`]s with the specified precision, the [`Float`] with fewer 1s in
1634    /// its binary expansion is chosen. See [`RoundingMode`] for a description of the `Nearest`
1635    /// rounding mode.
1636    ///
1637    /// The logarithm of any nonzero negative number is `NaN`.
1638    ///
1639    /// $$
1640    /// f(x) = \ln{x}+\varepsilon.
1641    /// $$
1642    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1643    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
1644    ///   \ln{x}\rfloor-p}$, where $p$ is the maximum precision of the inputs.
1645    ///
1646    /// Special cases:
1647    /// - $f(\text{NaN})=\text{NaN}$
1648    /// - $f(\infty)=\infty$
1649    /// - $f(-\infty)=\text{NaN}$
1650    /// - $f(\pm0.0)=-\infty$
1651    ///
1652    /// Neither overflow nor underflow is possible.
1653    ///
1654    /// If you want to use a rounding mode other than `Nearest`, consider using [`Float::ln_prec`]
1655    /// instead. If you want to specify the output precision, consider using [`Float::ln_round`]. If
1656    /// you want both of these things, consider using [`Float::ln_prec_round`].
1657    ///
1658    /// # Worst-case complexity
1659    /// $T(n) = O(n (\log n)^2 \log\log n)$
1660    ///
1661    /// $M(n) = O(n \log n)$
1662    ///
1663    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.get_prec()`.
1664    ///
1665    /// # Examples
1666    /// ```
1667    /// use malachite_base::num::arithmetic::traits::Ln;
1668    /// use malachite_base::num::basic::traits::{Infinity, NaN, NegativeInfinity};
1669    /// use malachite_float::Float;
1670    ///
1671    /// assert!(Float::NAN.ln().is_nan());
1672    /// assert_eq!(Float::INFINITY.ln(), Float::INFINITY);
1673    /// assert!(Float::NEGATIVE_INFINITY.ln().is_nan());
1674    /// assert_eq!(
1675    ///     Float::from_unsigned_prec(10u32, 100).0.ln().to_string(),
1676    ///     "2.3025850929940456840179914546838"
1677    /// );
1678    /// assert!(Float::from_signed_prec(-10, 100).0.ln().is_nan());
1679    /// ```
1680    #[inline]
1681    fn ln(self) -> Self {
1682        let prec = self.significant_bits();
1683        self.ln_prec_round(prec, Nearest).0
1684    }
1685}
1686
1687impl Ln for &Float {
1688    type Output = Float;
1689
1690    /// Computes the natural logarithm of a [`Float`], taking it by reference.
1691    ///
1692    /// If the output has a precision, it is the precision of the input. If the logarithm is
1693    /// equidistant from two [`Float`]s with the specified precision, the [`Float`] with fewer 1s in
1694    /// its binary expansion is chosen. See [`RoundingMode`] for a description of the `Nearest`
1695    /// rounding mode.
1696    ///
1697    /// The logarithm of any nonzero negative number is `NaN`.
1698    ///
1699    /// $$
1700    /// f(x) = \ln{x}+\varepsilon.
1701    /// $$
1702    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1703    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
1704    ///   \ln{x}\rfloor-p}$, where $p$ is the maximum precision of the inputs.
1705    ///
1706    /// Special cases:
1707    /// - $f(\text{NaN})=\text{NaN}$
1708    /// - $f(\infty)=\infty$
1709    /// - $f(-\infty)=\text{NaN}$
1710    /// - $f(\pm0.0)=-\infty$
1711    ///
1712    /// Neither overflow nor underflow is possible.
1713    ///
1714    /// If you want to use a rounding mode other than `Nearest`, consider using
1715    /// [`Float::ln_prec_ref`] instead. If you want to specify the output precision, consider using
1716    /// [`Float::ln_round_ref`]. If you want both of these things, consider using
1717    /// [`Float::ln_prec_round_ref`].
1718    ///
1719    /// # Worst-case complexity
1720    /// $T(n) = O(n (\log n)^2 \log\log n)$
1721    ///
1722    /// $M(n) = O(n \log n)$
1723    ///
1724    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.get_prec()`.
1725    ///
1726    /// # Examples
1727    /// ```
1728    /// use malachite_base::num::arithmetic::traits::Ln;
1729    /// use malachite_base::num::basic::traits::{Infinity, NaN, NegativeInfinity};
1730    /// use malachite_float::Float;
1731    ///
1732    /// assert!((&Float::NAN).ln().is_nan());
1733    /// assert_eq!((&Float::INFINITY).ln(), Float::INFINITY);
1734    /// assert!((&Float::NEGATIVE_INFINITY).ln().is_nan());
1735    /// assert_eq!(
1736    ///     (&Float::from_unsigned_prec(10u32, 100).0).ln().to_string(),
1737    ///     "2.3025850929940456840179914546838"
1738    /// );
1739    /// assert!((&Float::from_signed_prec(-10, 100).0).ln().is_nan());
1740    /// ```
1741    #[inline]
1742    fn ln(self) -> Float {
1743        let prec = self.significant_bits();
1744        self.ln_prec_round_ref(prec, Nearest).0
1745    }
1746}
1747
1748impl LnAssign for Float {
1749    /// Computes the natural logarithm of a [`Float`] in place.
1750    ///
1751    /// If the output has a precision, it is the precision of the input. If the logarithm is
1752    /// equidistant from two [`Float`]s with the specified precision, the [`Float`] with fewer 1s in
1753    /// its binary expansion is chosen. See [`RoundingMode`] for a description of the `Nearest`
1754    /// rounding mode.
1755    ///
1756    /// The logarithm of any nonzero negative number is `NaN`.
1757    ///
1758    /// $$
1759    /// x\gets = \ln{x}+\varepsilon.
1760    /// $$
1761    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1762    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
1763    ///   \ln{x}\rfloor-p}$, where $p$ is the maximum precision of the inputs.
1764    ///
1765    /// See the [`Float::ln`] documentation for information on special cases, overflow, and
1766    /// underflow.
1767    ///
1768    /// If you want to use a rounding mode other than `Nearest`, consider using
1769    /// [`Float::ln_prec_assign`] instead. If you want to specify the output precision, consider
1770    /// using [`Float::ln_round_assign`]. If you want both of these things, consider using
1771    /// [`Float::ln_prec_round_assign`].
1772    ///
1773    /// # Worst-case complexity
1774    /// $T(n) = O(n (\log n)^2 \log\log n)$
1775    ///
1776    /// $M(n) = O(n \log n)$
1777    ///
1778    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.get_prec()`.
1779    ///
1780    /// # Examples
1781    /// ```
1782    /// use malachite_base::num::arithmetic::traits::LnAssign;
1783    /// use malachite_base::num::basic::traits::{Infinity, NaN, NegativeInfinity};
1784    /// use malachite_float::Float;
1785    ///
1786    /// let mut x = Float::NAN;
1787    /// x.ln_assign();
1788    /// assert!(x.is_nan());
1789    ///
1790    /// let mut x = Float::INFINITY;
1791    /// x.ln_assign();
1792    /// assert_eq!(x, Float::INFINITY);
1793    ///
1794    /// let mut x = Float::NEGATIVE_INFINITY;
1795    /// x.ln_assign();
1796    /// assert!(x.is_nan());
1797    ///
1798    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
1799    /// x.ln_assign();
1800    /// assert_eq!(x.to_string(), "2.3025850929940456840179914546838");
1801    ///
1802    /// let mut x = Float::from_signed_prec(-10, 100).0;
1803    /// x.ln_assign();
1804    /// assert!(x.is_nan());
1805    /// ```
1806    #[inline]
1807    fn ln_assign(&mut self) {
1808        let prec = self.significant_bits();
1809        self.ln_prec_round_assign(prec, Nearest);
1810    }
1811}
1812
1813/// Computes the natural logarithm of a primitive float. Using this function is more accurate than
1814/// using the default `log` function or the one provided by `libm`.
1815///
1816/// The reciprocal logarithm of any nonzero negative number is `NaN`.
1817///
1818/// $$
1819/// f(x) = \ln x+\varepsilon.
1820/// $$
1821/// - If $\ln x$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1822/// - If $\ln x$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2 \ln x\rfloor-p}$,
1823///   where $p$ is precision of the output (typically 24 if `T` is a [`f32`] and 53 if `T` is a
1824///   [`f64`], but less if the output is subnormal).
1825///
1826/// Special cases:
1827/// - $f(\text{NaN})=\text{NaN}$
1828/// - $f(\infty)=\infty$
1829/// - $f(-\infty)=\text{NaN}$
1830/// - $f(\pm0.0)=-\infty$
1831///
1832/// Neither overflow nor underflow is possible.
1833///
1834/// # Worst-case complexity
1835/// Constant time and additional memory.
1836///
1837/// # Examples
1838/// ```
1839/// use malachite_base::num::basic::traits::NegativeInfinity;
1840/// use malachite_base::num::float::NiceFloat;
1841/// use malachite_float::float::arithmetic::ln::primitive_float_ln;
1842///
1843/// assert!(primitive_float_ln(f32::NAN).is_nan());
1844/// assert_eq!(
1845///     NiceFloat(primitive_float_ln(f32::INFINITY)),
1846///     NiceFloat(f32::INFINITY)
1847/// );
1848/// assert!(primitive_float_ln(f32::NEGATIVE_INFINITY).is_nan());
1849/// assert_eq!(NiceFloat(primitive_float_ln(10.0f32)), NiceFloat(2.3025851));
1850/// assert!(primitive_float_ln(-10.0f32).is_nan());
1851/// ```
1852#[inline]
1853#[allow(clippy::type_repetition_in_bounds)]
1854pub fn primitive_float_ln<T: PrimitiveFloat>(x: T) -> T
1855where
1856    Float: From<T> + PartialOrd<T>,
1857    for<'a> T: ExactFrom<&'a Float> + RoundingFrom<&'a Float>,
1858{
1859    emulate_float_to_float_fn(Float::ln_prec, x)
1860}
1861
1862/// Computes the natural logarithm of a [`Rational`], returning a primitive float result.
1863///
1864/// If the logarithm is equidistant from two primitive floats, the primitive float with fewer 1s in
1865/// its binary expansion is chosen. See [`RoundingMode`] for a description of the `Nearest` rounding
1866/// mode.
1867///
1868/// The logarithm of any negative number is `NaN`.
1869///
1870/// $$
1871/// f(x) = \ln{x}+\varepsilon.
1872/// $$
1873/// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1874/// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2 |\ln{x}|\rfloor-p}$,
1875///   where $p$ is precision of the output (typically 24 if `T` is a [`f32`] and 53 if `T` is a
1876///   [`f64`], but less if the output is subnormal).
1877///
1878/// Special cases:
1879/// - $f(0)=-\infty$
1880///
1881/// Neither overflow nor underflow is possible.
1882///
1883/// # Worst-case complexity
1884/// $T(m) = O(m)$
1885///
1886/// $M(m) = O(m)$
1887///
1888/// where $T$ is time, $M$ is additional memory, and $m$ is `x.significant_bits()`.
1889///
1890/// # Examples
1891/// ```
1892/// use malachite_base::num::basic::traits::{NegativeInfinity, Zero};
1893/// use malachite_base::num::float::NiceFloat;
1894/// use malachite_float::float::arithmetic::ln::primitive_float_ln_rational;
1895/// use malachite_q::Rational;
1896///
1897/// assert_eq!(
1898///     NiceFloat(primitive_float_ln_rational::<f64>(&Rational::ZERO)),
1899///     NiceFloat(f64::NEGATIVE_INFINITY)
1900/// );
1901/// assert_eq!(
1902///     NiceFloat(primitive_float_ln_rational::<f64>(
1903///         &Rational::from_unsigneds(1u8, 3)
1904///     )),
1905///     NiceFloat(-1.0986122886681098)
1906/// );
1907/// assert_eq!(
1908///     NiceFloat(primitive_float_ln_rational::<f64>(&Rational::from(10000))),
1909///     NiceFloat(9.210340371976184)
1910/// );
1911/// assert_eq!(
1912///     NiceFloat(primitive_float_ln_rational::<f64>(&Rational::from(-10000))),
1913///     NiceFloat(f64::NAN)
1914/// );
1915/// ```
1916#[inline]
1917#[allow(clippy::type_repetition_in_bounds)]
1918pub fn primitive_float_ln_rational<T: PrimitiveFloat>(x: &Rational) -> T
1919where
1920    Float: PartialOrd<T>,
1921    for<'a> T: ExactFrom<&'a Float> + RoundingFrom<&'a Float>,
1922{
1923    emulate_rational_to_float_fn(Float::ln_rational_prec_ref, x)
1924}