Skip to main content

malachite_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::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,
20};
21use core::cmp::Ordering::{self, *};
22use core::mem::swap;
23use malachite_base::num::arithmetic::traits::{
24    Agm, CeilingLogBase2, IsPowerOf2, Ln, LnAssign, Sign,
25};
26use malachite_base::num::basic::floats::PrimitiveFloat;
27use malachite_base::num::basic::integers::PrimitiveInt;
28use malachite_base::num::basic::traits::{One, Zero as ZeroTrait};
29use malachite_base::num::conversion::traits::{ExactFrom, RoundingFrom, SaturatingFrom};
30use malachite_base::num::logic::traits::SignificantBits;
31use malachite_base::rounding_modes::RoundingMode::{self, *};
32use malachite_nz::natural::arithmetic::float_extras::float_can_round;
33use malachite_nz::platform::Limb;
34use malachite_q::Rational;
35
36// The computation of log(x) is done using the formula: if we want p bits of the result,
37// ```
38//                    pi
39//      log(x) ~ ------------- - m log 2
40//               2 AG(1,4 / s)
41// ```
42// where s = x 2^m > 2^(p/2).
43//
44// More precisely, if F(x) = int(1 / ln(1 - (1 - x ^ 2) * sin(t) ^ 2), t = 0..pi / 2), then for s >=
45// 1.26 we have log(s) < F(4 / s) < log(s) * (1 + 4 / s ^ 2) from which we deduce pi / 2 / AG(1, 4 /
46// s) * (1 - 4 / s ^ 2) < log(s) < pi / 2 / AG(1, 4 / s) so the relative error 4 / s ^ 2 is < 4 / 2
47// ^ p i.e. 4 ulps.
48//
49// This is mpfr_log from log.c, MPFR 4.2.0.
50fn ln_prec_round_normal_ref(x: &Float, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
51    if *x == 1u32 {
52        return (Float::ZERO, Equal);
53    }
54    assert_ne!(rm, Exact, "Inexact ln");
55    let x_exp = i64::from(x.get_exponent().unwrap());
56    // use initial precision about q + 2 * lg(q) + cte
57    let mut working_prec = prec + (prec.ceiling_log_base_2() << 1) + 10;
58    let mut increment = Limb::WIDTH;
59    let mut previous_m = 0;
60    let mut x = x.clone();
61    loop {
62        // Calculus of m (depends on p)
63        let m = i64::exact_from((working_prec + 3) >> 1)
64            .checked_sub(x_exp)
65            .unwrap();
66        x <<= m - previous_m;
67        previous_m = m;
68        assert!(x.is_normal());
69        let tmp2 = Float::pi_prec(working_prec).0
70            / (Float::ONE.agm(
71                const { Float::const_from_unsigned(4) }
72                    .div_prec_round_val_ref(&x, working_prec, Floor)
73                    .0,
74            ) << 1u32);
75        let exp2 = tmp2.get_exponent();
76        let tmp1 = tmp2
77            - Float::ln_2_prec(working_prec)
78                .0
79                .mul_prec(Float::from(m), working_prec)
80                .0;
81        if let (Some(exp1), Some(exp2)) = (tmp1.get_exponent(), exp2) {
82            let cancel = u64::saturating_from(exp2 - exp1);
83            // we have 7 ulps of error from the above roundings, 4 ulps from the 4 / s ^ 2 second
84            // order term, plus the canceled bits
85            if float_can_round(
86                tmp1.significand_ref().unwrap(),
87                working_prec.saturating_sub(cancel).saturating_sub(4),
88                prec,
89                rm,
90            ) {
91                return Float::from_float_prec_round(tmp1, prec, rm);
92            }
93            working_prec += cancel + working_prec.ceiling_log_base_2();
94        } else {
95            working_prec += working_prec.ceiling_log_base_2();
96        }
97        working_prec += increment;
98        increment = working_prec >> 1;
99    }
100}
101
102// This is mpfr_log from log.c, MPFR 4.2.0.
103fn ln_prec_round_normal(mut x: Float, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
104    if x == 1u32 {
105        return (Float::ZERO, Equal);
106    }
107    assert_ne!(rm, Exact, "Inexact ln");
108    let x_exp = i64::from(x.get_exponent().unwrap());
109    // use initial precision about q + 2 * lg(q) + cte
110    let mut working_prec = prec + (prec.ceiling_log_base_2() << 1) + 10;
111    let mut increment = Limb::WIDTH;
112    let mut previous_m = 0;
113    loop {
114        // Calculus of m (depends on p)
115        let m = i64::exact_from((working_prec + 3) >> 1)
116            .checked_sub(x_exp)
117            .unwrap();
118        x <<= m - previous_m;
119        previous_m = m;
120        assert!(x.is_normal());
121        let tmp2 = Float::pi_prec(working_prec).0
122            / (Float::ONE.agm(
123                const { Float::const_from_unsigned(4) }
124                    .div_prec_round_val_ref(&x, working_prec, Floor)
125                    .0,
126            ) << 1u32);
127        let exp2 = tmp2.get_exponent();
128        let tmp1 = tmp2
129            - Float::ln_2_prec(working_prec)
130                .0
131                .mul_prec(Float::from(m), working_prec)
132                .0;
133        if let (Some(exp1), Some(exp2)) = (tmp1.get_exponent(), exp2) {
134            let cancel = u64::saturating_from(exp2 - exp1);
135            // we have 7 ulps of error from the above roundings, 4 ulps from the 4 / s ^ 2 second
136            // order term, plus the canceled bits
137            if float_can_round(
138                tmp1.significand_ref().unwrap(),
139                working_prec.saturating_sub(cancel).saturating_sub(4),
140                prec,
141                rm,
142            ) {
143                return Float::from_float_prec_round(tmp1, prec, rm);
144            }
145            working_prec += cancel + working_prec.ceiling_log_base_2();
146        } else {
147            working_prec += working_prec.ceiling_log_base_2();
148        }
149        working_prec += increment;
150        increment = working_prec >> 1;
151    }
152}
153
154pub(crate) fn ln_prec_round_normal_extended(
155    x: ExtendedFloat,
156    prec: u64,
157    rm: RoundingMode,
158) -> (Float, Ordering) {
159    if x.exp == 1 && x.x.is_power_of_2() {
160        return (Float::ZERO, Equal);
161    }
162    assert_ne!(rm, Exact, "Inexact ln");
163    let x_exp = x.exp;
164    // use initial precision about q + 2 * lg(q) + cte
165    let mut working_prec = prec + (prec.ceiling_log_base_2() << 1) + 10;
166    let mut increment = Limb::WIDTH;
167    let mut m = i64::exact_from((working_prec + 3) >> 1)
168        .checked_sub(x.exp)
169        .unwrap();
170    let mut previous_m = m;
171    let mut x = Float::exact_from(x << m);
172    let mut first = true;
173    loop {
174        if first {
175            first = false;
176        } else {
177            // Calculus of m (depends on p)
178            m = i64::exact_from((working_prec + 3) >> 1)
179                .checked_sub(x_exp)
180                .unwrap();
181            x <<= m - previous_m;
182            previous_m = m;
183        }
184        assert!(x.is_normal());
185        let tmp2 = Float::pi_prec(working_prec).0
186            / (Float::ONE.agm(
187                const { Float::const_from_unsigned(4) }
188                    .div_prec_round_val_ref(&x, working_prec, Floor)
189                    .0,
190            ) << 1u32);
191        let exp2 = tmp2.get_exponent();
192        let tmp1 = tmp2
193            - Float::ln_2_prec(working_prec)
194                .0
195                .mul_prec(Float::from(m), working_prec)
196                .0;
197        if let (Some(exp1), Some(exp2)) = (tmp1.get_exponent(), exp2) {
198            let cancel = u64::saturating_from(exp2 - exp1);
199            // we have 7 ulps of error from the above roundings, 4 ulps from the 4 / s ^ 2 second
200            // order term, plus the canceled bits
201            if float_can_round(
202                tmp1.significand_ref().unwrap(),
203                working_prec.saturating_sub(cancel).saturating_sub(4),
204                prec,
205                rm,
206            ) {
207                return Float::from_float_prec_round(tmp1, prec, rm);
208            }
209            working_prec += cancel + working_prec.ceiling_log_base_2();
210        } else {
211            working_prec += working_prec.ceiling_log_base_2();
212        }
213        working_prec += increment;
214        increment = working_prec >> 1;
215    }
216}
217
218fn ln_rational_helper(x: &Rational, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
219    let mut working_prec = prec + 10;
220    let mut increment = Limb::WIDTH;
221    loop {
222        let (x_lo, x_o) = Float::from_rational_prec_round_ref(x, working_prec, Floor);
223        if x_o == Equal {
224            return ln_prec_round_normal(x_lo, prec, rm);
225        }
226        let mut x_hi = x_lo.clone();
227        x_hi.increment();
228        let (ln_lo, mut o_lo) = ln_prec_round_normal(x_lo, prec, rm);
229        let (ln_hi, mut o_hi) = ln_prec_round_normal(x_hi, prec, rm);
230        if o_lo == Equal {
231            o_lo = o_hi;
232        }
233        if o_hi == Equal {
234            o_hi = o_lo;
235        }
236        if o_lo == o_hi && ln_lo == ln_hi {
237            return (ln_lo, o_lo);
238        }
239        working_prec += increment;
240        increment = working_prec >> 1;
241    }
242}
243
244fn ln_rational_helper_extended(x: &Rational, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
245    let mut working_prec = prec + 10;
246    let mut increment = Limb::WIDTH;
247    loop {
248        let (x_lo, x_o) = ExtendedFloat::from_rational_prec_round_ref(x, working_prec, Floor);
249        if x_o == Equal {
250            return ln_prec_round_normal_extended(x_lo, prec, rm);
251        }
252        let mut x_hi = x_lo.clone();
253        x_hi.increment();
254        let (ln_lo, mut o_lo) = ln_prec_round_normal_extended(x_lo, prec, rm);
255        let (ln_hi, mut o_hi) = ln_prec_round_normal_extended(x_hi, prec, rm);
256        if o_lo == Equal {
257            o_lo = o_hi;
258        }
259        if o_hi == Equal {
260            o_hi = o_lo;
261        }
262        if o_lo == o_hi && ln_lo == ln_hi {
263            return (ln_lo, o_lo);
264        }
265        working_prec += increment;
266        increment = working_prec >> 1;
267    }
268}
269
270impl Float {
271    /// Computes the natural logarithm of a [`Float`], rounding the result to the specified
272    /// precision and with the specified rounding mode. The [`Float`] is taken by value. An
273    /// [`Ordering`] is also returned, indicating whether the rounded logarithm is less than, equal
274    /// to, or greater than the exact logarithm. Although `NaN`s are not comparable to any
275    /// [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
276    ///
277    /// The logarithm of any nonzero negative number is `NaN`.
278    ///
279    /// See [`RoundingMode`] for a description of the possible rounding modes.
280    ///
281    /// $$
282    /// f(x,p,m) = \ln{x}+\varepsilon.
283    /// $$
284    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
285    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
286    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p+1}$.
287    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
288    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p}$.
289    ///
290    /// If the output has a precision, it is `prec`.
291    ///
292    /// Special cases:
293    /// - $f(\text{NaN},p,m)=\text{NaN}$
294    /// - $f(\infty,p,m)=\infty$
295    /// - $f(-\infty,p,m)=\text{NaN}$
296    /// - $f(\pm0.0,p,m)=-\infty$
297    ///
298    /// Neither overflow nor underflow is possible.
299    ///
300    /// If you know you'll be using `Nearest`, consider using [`Float::ln_prec`] instead. If you
301    /// know that your target precision is the precision of the input, consider using
302    /// [`Float::ln_round`] instead. If both of these things are true, consider using [`Float::ln`]
303    /// instead.
304    ///
305    /// # Worst-case complexity
306    /// $T(n) = O(n (\log n)^2 \log\log n)$
307    ///
308    /// $M(n) = O(n (\log n)^2)$
309    ///
310    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
311    ///
312    /// # Panics
313    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the given
314    /// precision.
315    ///
316    /// # Examples
317    /// ```
318    /// use malachite_base::rounding_modes::RoundingMode::*;
319    /// use malachite_float::Float;
320    /// use std::cmp::Ordering::*;
321    ///
322    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
323    ///     .0
324    ///     .ln_prec_round(5, Floor);
325    /// assert_eq!(ln.to_string(), "2.2");
326    /// assert_eq!(o, Less);
327    ///
328    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
329    ///     .0
330    ///     .ln_prec_round(5, Ceiling);
331    /// assert_eq!(ln.to_string(), "2.4");
332    /// assert_eq!(o, Greater);
333    ///
334    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
335    ///     .0
336    ///     .ln_prec_round(5, Nearest);
337    /// assert_eq!(ln.to_string(), "2.2");
338    /// assert_eq!(o, Less);
339    ///
340    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
341    ///     .0
342    ///     .ln_prec_round(20, Floor);
343    /// assert_eq!(ln.to_string(), "2.302582");
344    /// assert_eq!(o, Less);
345    ///
346    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
347    ///     .0
348    ///     .ln_prec_round(20, Ceiling);
349    /// assert_eq!(ln.to_string(), "2.302586");
350    /// assert_eq!(o, Greater);
351    ///
352    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
353    ///     .0
354    ///     .ln_prec_round(20, Nearest);
355    /// assert_eq!(ln.to_string(), "2.302586");
356    /// assert_eq!(o, Greater);
357    /// ```
358    #[inline]
359    pub fn ln_prec_round(self, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
360        assert_ne!(prec, 0);
361        match self {
362            Self(NaN | Infinity { sign: false } | Finite { sign: false, .. }) => {
363                (float_nan!(), Equal)
364            }
365            float_either_zero!() => (float_negative_infinity!(), Equal),
366            float_infinity!() => (float_infinity!(), Equal),
367            _ => ln_prec_round_normal(self, prec, rm),
368        }
369    }
370
371    /// Computes the natural logarithm of a [`Float`], rounding the result to the specified
372    /// precision and with the specified rounding mode. The [`Float`] is taken by reference. An
373    /// [`Ordering`] is also returned, indicating whether the rounded logarithm is less than, equal
374    /// to, or greater than the exact logarithm. Although `NaN`s are not comparable to any
375    /// [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
376    ///
377    /// The logarithm of any nonzero negative number is `NaN`.
378    ///
379    /// See [`RoundingMode`] for a description of the possible rounding modes.
380    ///
381    /// $$
382    /// f(x,p,m) = \ln{x}+\varepsilon.
383    /// $$
384    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
385    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
386    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p+1}$.
387    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
388    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p}$.
389    ///
390    /// If the output has a precision, it is `prec`.
391    ///
392    /// Special cases:
393    /// - $f(\text{NaN},p,m)=\text{NaN}$
394    /// - $f(\infty,p,m)=\infty$
395    /// - $f(-\infty,p,m)=\text{NaN}$
396    /// - $f(\pm0.0,p,m)=-\infty$
397    ///
398    /// Neither overflow nor underflow is possible.
399    ///
400    /// If you know you'll be using `Nearest`, consider using [`Float::ln_prec_ref`] instead. If you
401    /// know that your target precision is the precision of the input, consider using
402    /// [`Float::ln_round_ref`] instead. If both of these things are true, consider using
403    /// `(&Float).ln()`instead.
404    ///
405    /// # Worst-case complexity
406    /// $T(n) = O(n (\log n)^2 \log\log n)$
407    ///
408    /// $M(n) = O(n (\log n)^2)$
409    ///
410    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
411    ///
412    /// # Panics
413    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the given
414    /// precision.
415    ///
416    /// # Examples
417    /// ```
418    /// use malachite_base::rounding_modes::RoundingMode::*;
419    /// use malachite_float::Float;
420    /// use std::cmp::Ordering::*;
421    ///
422    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
423    ///     .0
424    ///     .ln_prec_round_ref(5, Floor);
425    /// assert_eq!(ln.to_string(), "2.2");
426    /// assert_eq!(o, Less);
427    ///
428    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
429    ///     .0
430    ///     .ln_prec_round_ref(5, Ceiling);
431    /// assert_eq!(ln.to_string(), "2.4");
432    /// assert_eq!(o, Greater);
433    ///
434    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
435    ///     .0
436    ///     .ln_prec_round_ref(5, Nearest);
437    /// assert_eq!(ln.to_string(), "2.2");
438    /// assert_eq!(o, Less);
439    ///
440    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
441    ///     .0
442    ///     .ln_prec_round_ref(20, Floor);
443    /// assert_eq!(ln.to_string(), "2.302582");
444    /// assert_eq!(o, Less);
445    ///
446    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
447    ///     .0
448    ///     .ln_prec_round_ref(20, Ceiling);
449    /// assert_eq!(ln.to_string(), "2.302586");
450    /// assert_eq!(o, Greater);
451    ///
452    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
453    ///     .0
454    ///     .ln_prec_round_ref(20, Nearest);
455    /// assert_eq!(ln.to_string(), "2.302586");
456    /// assert_eq!(o, Greater);
457    /// ```
458    #[inline]
459    pub fn ln_prec_round_ref(&self, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
460        assert_ne!(prec, 0);
461        match self {
462            Self(NaN | Infinity { sign: false } | Finite { sign: false, .. }) => {
463                (float_nan!(), Equal)
464            }
465            float_either_zero!() => (float_negative_infinity!(), Equal),
466            float_infinity!() => (float_infinity!(), Equal),
467            _ => ln_prec_round_normal_ref(self, prec, rm),
468        }
469    }
470
471    /// Computes the natural logarithm of a [`Float`], rounding the result to the nearest value of
472    /// the specified precision. The [`Float`] is taken by value. An [`Ordering`] is also returned,
473    /// indicating whether the rounded logarithm is less than, equal to, or greater than the exact
474    /// logarithm. Although `NaN`s are not comparable to any [`Float`], whenever this function
475    /// returns a `NaN` it also returns `Equal`.
476    ///
477    /// The logarithm of any nonzero negative number is `NaN`.
478    ///
479    /// If the logarithm is equidistant from two [`Float`]s with the specified precision, the
480    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
481    /// description of the `Nearest` rounding mode.
482    ///
483    /// $$
484    /// f(x,p) = \ln{x}+\varepsilon.
485    /// $$
486    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
487    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
488    ///   \ln{x}\rfloor-p}$.
489    ///
490    /// If the output has a precision, it is `prec`.
491    ///
492    /// Special cases:
493    /// - $f(\text{NaN},p,m)=\text{NaN}$
494    /// - $f(\infty,p,m)=\infty$
495    /// - $f(-\infty,p,m)=\text{NaN}$
496    /// - $f(\pm0.0,p,m)=-\infty$
497    ///
498    /// Neither overflow nor underflow is possible.
499    ///
500    /// If you want to use a rounding mode other than `Nearest`, consider using
501    /// [`Float::ln_prec_round`] instead. If you know that your target precision is the precision of
502    /// the input, consider using [`Float::ln`] instead.
503    ///
504    /// # Worst-case complexity
505    /// $T(n) = O(n (\log n)^2 \log\log n)$
506    ///
507    /// $M(n) = O(n (\log n)^2)$
508    ///
509    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
510    ///
511    /// # Examples
512    /// ```
513    /// use malachite_float::Float;
514    /// use std::cmp::Ordering::*;
515    ///
516    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_prec(5);
517    /// assert_eq!(ln.to_string(), "2.2");
518    /// assert_eq!(o, Less);
519    ///
520    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_prec(20);
521    /// assert_eq!(ln.to_string(), "2.302586");
522    /// assert_eq!(o, Greater);
523    /// ```
524    #[inline]
525    pub fn ln_prec(self, prec: u64) -> (Self, Ordering) {
526        self.ln_prec_round(prec, Nearest)
527    }
528
529    /// Computes the natural logarithm of a [`Float`], rounding the result to the nearest value of
530    /// the specified precision. The [`Float`] is taken by reference. An [`Ordering`] is also
531    /// returned, indicating whether the rounded logarithm is less than, equal to, or greater than
532    /// the exact logarithm. Although `NaN`s are not comparable to any [`Float`], whenever this
533    /// function returns a `NaN` it also returns `Equal`.
534    ///
535    /// The logarithm of any nonzero negative number is `NaN`.
536    ///
537    /// If the logarithm is equidistant from two [`Float`]s with the specified precision, the
538    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
539    /// description of the `Nearest` rounding mode.
540    ///
541    /// $$
542    /// f(x,p) = \ln{x}+\varepsilon.
543    /// $$
544    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
545    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
546    ///   \ln{x}\rfloor-p}$.
547    ///
548    /// If the output has a precision, it is `prec`.
549    ///
550    /// Special cases:
551    /// - $f(\text{NaN},p)=\text{NaN}$
552    /// - $f(\infty,p)=\infty$
553    /// - $f(-\infty,p)=\text{NaN}$
554    /// - $f(\pm0.0,p)=-\infty$
555    ///
556    /// Neither overflow nor underflow is possible.
557    ///
558    /// If you want to use a rounding mode other than `Nearest`, consider using
559    /// [`Float::ln_prec_round_ref`] instead. If you know that your target precision is the
560    /// precision of the input, consider using `(&Float).ln()` instead.
561    ///
562    /// # Worst-case complexity
563    /// $T(n) = O(n (\log n)^2 \log\log n)$
564    ///
565    /// $M(n) = O(n (\log n)^2)$
566    ///
567    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
568    ///
569    /// # Examples
570    /// ```
571    /// use malachite_float::Float;
572    /// use std::cmp::Ordering::*;
573    ///
574    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_prec_ref(5);
575    /// assert_eq!(ln.to_string(), "2.2");
576    /// assert_eq!(o, Less);
577    ///
578    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_prec_ref(20);
579    /// assert_eq!(ln.to_string(), "2.302586");
580    /// assert_eq!(o, Greater);
581    /// ```
582    #[inline]
583    pub fn ln_prec_ref(&self, prec: u64) -> (Self, Ordering) {
584        self.ln_prec_round_ref(prec, Nearest)
585    }
586
587    /// Computes the natural logarithm of a [`Float`], rounding the result with the specified
588    /// rounding mode. The [`Float`] is taken by value. An [`Ordering`] is also returned, indicating
589    /// whether the rounded logarithm is less than, equal to, or greater than the exact logarithm.
590    /// Although `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN`
591    /// it also returns `Equal`.
592    ///
593    /// The logarithm of any nonzero negative number is `NaN`.
594    ///
595    /// The precision of the output is the precision of the input. See [`RoundingMode`] for a
596    /// description of the possible rounding modes.
597    ///
598    /// $$
599    /// f(x,m) = \ln{x}+\varepsilon.
600    /// $$
601    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
602    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
603    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p+1}$, where $p$ is the precision of the input.
604    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
605    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p}$, where $p$ is the precision of the input.
606    ///
607    /// If the output has a precision, it is the precision of the input.
608    ///
609    /// Special cases:
610    /// - $f(\text{NaN},m)=\text{NaN}$
611    /// - $f(\infty,m)=\infty$
612    /// - $f(-\infty,m)=\text{NaN}$
613    /// - $f(\pm0.0,m)=-\infty$
614    ///
615    /// Neither overflow nor underflow is possible.
616    ///
617    /// If you want to specify an output precision, consider using [`Float::ln_prec_round`] instead.
618    /// If you know you'll be using the `Nearest` rounding mode, consider using [`Float::ln`]
619    /// instead.
620    ///
621    /// # Worst-case complexity
622    /// $T(n) = O(n (\log n)^2 \log\log n)$
623    ///
624    /// $M(n) = O(n (\log n)^2)$
625    ///
626    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.get_prec()`.
627    ///
628    /// # Panics
629    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the input
630    /// precision.
631    ///
632    /// # Examples
633    /// ```
634    /// use malachite_base::rounding_modes::RoundingMode::*;
635    /// use malachite_float::Float;
636    /// use std::cmp::Ordering::*;
637    ///
638    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_round(Floor);
639    /// assert_eq!(ln.to_string(), "2.302585092994045684017991454684");
640    /// assert_eq!(o, Less);
641    ///
642    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_round(Ceiling);
643    /// assert_eq!(ln.to_string(), "2.302585092994045684017991454687");
644    /// assert_eq!(o, Greater);
645    ///
646    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_round(Nearest);
647    /// assert_eq!(ln.to_string(), "2.302585092994045684017991454684");
648    /// assert_eq!(o, Less);
649    /// ```
650    #[inline]
651    pub fn ln_round(self, rm: RoundingMode) -> (Self, Ordering) {
652        let prec = self.significant_bits();
653        self.ln_prec_round(prec, rm)
654    }
655
656    /// Computes the natural logarithm of a [`Float`], rounding the result with the specified
657    /// rounding mode. The [`Float`] is taken by reference. An [`Ordering`] is also returned,
658    /// indicating whether the rounded logarithm is less than, equal to, or greater than the exact
659    /// logarithm. Although `NaN`s are not comparable to any [`Float`], whenever this function
660    /// returns a `NaN` it also returns `Equal`.
661    ///
662    /// The logarithm of any nonzero negative number is `NaN`.
663    ///
664    /// The precision of the output is the precision of the input. See [`RoundingMode`] for a
665    /// description of the possible rounding modes.
666    ///
667    /// $$
668    /// f(x,m) = \ln{x}+\varepsilon.
669    /// $$
670    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
671    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
672    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p+1}$, where $p$ is the precision of the input.
673    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
674    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p}$, where $p$ is the precision of the input.
675    ///
676    /// If the output has a precision, it is the precision of the input.
677    ///
678    /// Special cases:
679    /// - $f(\text{NaN},m)=\text{NaN}$
680    /// - $f(\infty,m)=\infty$
681    /// - $f(-\infty,m)=\text{NaN}$
682    /// - $f(\pm0.0,m)=-\infty$
683    ///
684    /// Neither overflow nor underflow is possible.
685    ///
686    /// If you want to specify an output precision, consider using [`Float::ln_prec_round_ref`]
687    /// instead. If you know you'll be using the `Nearest` rounding mode, consider using
688    /// `(&Float).ln()` instead.
689    ///
690    /// # Worst-case complexity
691    /// $T(n) = O(n (\log n)^2 \log\log n)$
692    ///
693    /// $M(n) = O(n (\log n)^2)$
694    ///
695    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.get_prec()`.
696    ///
697    /// # Panics
698    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the input
699    /// precision.
700    ///
701    /// # Examples
702    /// ```
703    /// use malachite_base::rounding_modes::RoundingMode::*;
704    /// use malachite_float::Float;
705    /// use std::cmp::Ordering::*;
706    ///
707    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_round_ref(Floor);
708    /// assert_eq!(ln.to_string(), "2.302585092994045684017991454684");
709    /// assert_eq!(o, Less);
710    ///
711    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
712    ///     .0
713    ///     .ln_round_ref(Ceiling);
714    /// assert_eq!(ln.to_string(), "2.302585092994045684017991454687");
715    /// assert_eq!(o, Greater);
716    ///
717    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
718    ///     .0
719    ///     .ln_round_ref(Nearest);
720    /// assert_eq!(ln.to_string(), "2.302585092994045684017991454684");
721    /// assert_eq!(o, Less);
722    /// ```
723    #[inline]
724    pub fn ln_round_ref(&self, rm: RoundingMode) -> (Self, Ordering) {
725        let prec = self.significant_bits();
726        self.ln_prec_round_ref(prec, rm)
727    }
728
729    /// Computes the natural logarithm of a [`Float`] in place, rounding the result to the specified
730    /// precision and with the specified rounding mode. An [`Ordering`] is returned, indicating
731    /// whether the rounded logarithm is less than, equal to, or greater than the exact logarithm.
732    /// Although `NaN`s are not comparable to any [`Float`], whenever this function sets the
733    /// [`Float`] to `NaN` it also returns `Equal`.
734    ///
735    /// The logarithm of any nonzero negative number is `NaN`.
736    ///
737    /// See [`RoundingMode`] for a description of the possible rounding modes.
738    ///
739    /// $$
740    /// x \gets \ln{x}+\varepsilon.
741    /// $$
742    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
743    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
744    ///   2^{\lfloor\log_2 |xy|\rfloor-p+1}$.
745    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
746    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p}$.
747    ///
748    /// If the output has a precision, it is `prec`.
749    ///
750    /// See the [`Float::ln_prec_round`] documentation for information on special cases, overflow,
751    /// and underflow.
752    ///
753    /// If you know you'll be using `Nearest`, consider using [`Float::ln_prec_assign`] instead. If
754    /// you know that your target precision is the precision of the input, consider using
755    /// [`Float::ln_round_assign`] instead. If both of these things are true, consider using
756    /// [`Float::ln_assign`] instead.
757    ///
758    /// # Worst-case complexity
759    /// $T(n) = O(n (\log n)^2 \log\log n)$
760    ///
761    /// $M(n) = O(n (\log n)^2)$
762    ///
763    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
764    ///
765    /// # Panics
766    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the given
767    /// precision.
768    ///
769    /// # Examples
770    /// ```
771    /// use malachite_base::rounding_modes::RoundingMode::*;
772    /// use malachite_float::Float;
773    /// use std::cmp::Ordering::*;
774    ///
775    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
776    /// assert_eq!(x.ln_prec_round_assign(5, Floor), Less);
777    /// assert_eq!(x.to_string(), "2.2");
778    ///
779    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
780    /// assert_eq!(x.ln_prec_round_assign(5, Ceiling), Greater);
781    /// assert_eq!(x.to_string(), "2.4");
782    ///
783    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
784    /// assert_eq!(x.ln_prec_round_assign(5, Nearest), Less);
785    /// assert_eq!(x.to_string(), "2.2");
786    ///
787    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
788    /// assert_eq!(x.ln_prec_round_assign(20, Floor), Less);
789    /// assert_eq!(x.to_string(), "2.302582");
790    ///
791    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
792    /// assert_eq!(x.ln_prec_round_assign(20, Ceiling), Greater);
793    /// assert_eq!(x.to_string(), "2.302586");
794    ///
795    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
796    /// assert_eq!(x.ln_prec_round_assign(20, Nearest), Greater);
797    /// assert_eq!(x.to_string(), "2.302586");
798    /// ```
799    #[inline]
800    pub fn ln_prec_round_assign(&mut self, prec: u64, rm: RoundingMode) -> Ordering {
801        let mut x = Self::ZERO;
802        swap(self, &mut x);
803        let o;
804        (*self, o) = x.ln_prec_round(prec, rm);
805        o
806    }
807
808    /// Computes the natural logarithm of a [`Float`] in place, rounding the result to the nearest
809    /// value of the specified precision. An [`Ordering`] is returned, indicating whether the
810    /// rounded logarithm is less than, equal to, or greater than the exact logarithm. Although
811    /// `NaN`s are not comparable to any [`Float`], whenever this function sets the [`Float`] to
812    /// `NaN` it also returns `Equal`.
813    ///
814    /// The logarithm of any nonzero negative number is `NaN`.
815    ///
816    /// If the logarithm is equidistant from two [`Float`]s with the specified precision, the
817    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
818    /// description of the `Nearest` rounding mode.
819    ///
820    /// $$
821    /// x \gets \ln{x}+\varepsilon.
822    /// $$
823    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
824    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
825    ///   \ln{x}\rfloor-p}$.
826    ///
827    /// If the output has a precision, it is `prec`.
828    ///
829    /// See the [`Float::ln_prec`] documentation for information on special cases, overflow, and
830    /// underflow.
831    ///
832    /// If you want to use a rounding mode other than `Nearest`, consider using
833    /// [`Float::ln_prec_round_assign`] instead. If you know that your target precision is the
834    /// precision of the input, consider using [`Float::ln`] instead.
835    ///
836    /// # Worst-case complexity
837    /// $T(n) = O(n (\log n)^2 \log\log n)$
838    ///
839    /// $M(n) = O(n (\log n)^2)$
840    ///
841    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
842    ///
843    /// # Examples
844    /// ```
845    /// use malachite_float::Float;
846    /// use std::cmp::Ordering::*;
847    ///
848    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
849    /// assert_eq!(x.ln_prec_assign(5), Less);
850    /// assert_eq!(x.to_string(), "2.2");
851    ///
852    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
853    /// assert_eq!(x.ln_prec_assign(20), Greater);
854    /// assert_eq!(x.to_string(), "2.302586");
855    /// ```
856    #[inline]
857    pub fn ln_prec_assign(&mut self, prec: u64) -> Ordering {
858        self.ln_prec_round_assign(prec, Nearest)
859    }
860
861    /// Computes the natural logarithm of a [`Float`] in place, rounding the result with the
862    /// specified rounding mode. An [`Ordering`] is returned, indicating whether the rounded
863    /// logarithm is less than, equal to, or greater than the exact logarithm. Although `NaN`s are
864    /// not comparable to any [`Float`], whenever this function sets the [`Float`] to `NaN` it also
865    /// returns `Equal`.
866    ///
867    /// The logarithm of any nonzero negative number is `NaN`.
868    ///
869    /// The precision of the output is the precision of the input. See [`RoundingMode`] for a
870    /// description of the possible rounding modes.
871    ///
872    /// $$
873    /// x \gets \ln{x}+\varepsilon.
874    /// $$
875    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
876    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
877    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p+1}$, where $p$ is the maximum precision of the inputs.
878    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
879    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p}$, where $p$ is the maximum precision of the inputs.
880    ///
881    /// If the output has a precision, it is the precision of the input.
882    ///
883    /// See the [`Float::ln_round`] documentation for information on special cases, overflow, and
884    /// underflow.
885    ///
886    /// If you want to specify an output precision, consider using [`Float::ln_prec_round_assign`]
887    /// instead. If you know you'll be using the `Nearest` rounding mode, consider using
888    /// [`Float::ln_assign`] instead.
889    ///
890    /// # Worst-case complexity
891    /// $T(n) = O(n (\log n)^2 \log\log n)$
892    ///
893    /// $M(n) = O(n (\log n)^2)$
894    ///
895    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.get_prec()`.
896    ///
897    /// # Panics
898    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the input
899    /// precision.
900    ///
901    /// # Examples
902    /// ```
903    /// use malachite_base::rounding_modes::RoundingMode::*;
904    /// use malachite_float::Float;
905    /// use std::cmp::Ordering::*;
906    ///
907    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
908    /// assert_eq!(x.ln_round_assign(Floor), Less);
909    /// assert_eq!(x.to_string(), "2.302585092994045684017991454684");
910    ///
911    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
912    /// assert_eq!(x.ln_round_assign(Ceiling), Greater);
913    /// assert_eq!(x.to_string(), "2.302585092994045684017991454687");
914    ///
915    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
916    /// assert_eq!(x.ln_round_assign(Nearest), Less);
917    /// assert_eq!(x.to_string(), "2.302585092994045684017991454684");
918    /// ```
919    #[inline]
920    pub fn ln_round_assign(&mut self, rm: RoundingMode) -> Ordering {
921        let prec = self.significant_bits();
922        self.ln_prec_round_assign(prec, rm)
923    }
924
925    /// Computes the natural logarithm of a [`Rational`], rounding the result to the specified
926    /// precision and with the specified rounding mode and returning the result as a [`Float`]. The
927    /// [`Rational`] is taken by value. An [`Ordering`] is also returned, indicating whether the
928    /// rounded logarithm is less than, equal to, or greater than the exact logarithm. Although
929    /// `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN` it also
930    /// returns `Equal`.
931    ///
932    /// The logarithm of any nonzero negative number is `NaN`.
933    ///
934    /// See [`RoundingMode`] for a description of the possible rounding modes.
935    ///
936    /// $$
937    /// f(x,p,m) = \ln{x}+\varepsilon.
938    /// $$
939    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
940    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
941    ///   2^{\lfloor\log_2 |\ln{x}|\rfloor-p+1}$.
942    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
943    ///   2^{\lfloor\log_2 |\ln{x}|\rfloor-p}$.
944    ///
945    /// If the output has a precision, it is `prec`.
946    ///
947    /// Special cases:
948    /// - $f(0.0,p,m)=-\infty$
949    ///
950    /// Neither overflow nor underflow is possible.
951    ///
952    /// If you know you'll be using `Nearest`, consider using [`Float::ln_rational_prec`] instead.
953    ///
954    /// # Worst-case complexity
955    /// $T(n) = O(n (\log n)^2 \log\log n)$
956    ///
957    /// $M(n) = O(n (\log n)^2)$
958    ///
959    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
960    ///
961    /// # Panics
962    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the given
963    /// precision.
964    ///
965    /// # Examples
966    /// ```
967    /// use malachite_base::rounding_modes::RoundingMode::*;
968    /// use malachite_float::Float;
969    /// use malachite_q::Rational;
970    /// use std::cmp::Ordering::*;
971    ///
972    /// let (ln, o) = Float::ln_rational_prec_round(Rational::from_unsigneds(3u8, 5), 5, Floor);
973    /// assert_eq!(ln.to_string(), "-0.53");
974    /// assert_eq!(o, Less);
975    ///
976    /// let (ln, o) = Float::ln_rational_prec_round(Rational::from_unsigneds(3u8, 5), 5, Ceiling);
977    /// assert_eq!(ln.to_string(), "-0.5");
978    /// assert_eq!(o, Greater);
979    ///
980    /// let (ln, o) = Float::ln_rational_prec_round(Rational::from_unsigneds(3u8, 5), 5, Nearest);
981    /// assert_eq!(ln.to_string(), "-0.5");
982    /// assert_eq!(o, Greater);
983    ///
984    /// let (ln, o) = Float::ln_rational_prec_round(Rational::from_unsigneds(3u8, 5), 20, Floor);
985    /// assert_eq!(ln.to_string(), "-0.510826");
986    /// assert_eq!(o, Less);
987    ///
988    /// let (ln, o) = Float::ln_rational_prec_round(Rational::from_unsigneds(3u8, 5), 20, Ceiling);
989    /// assert_eq!(ln.to_string(), "-0.510825");
990    /// assert_eq!(o, Greater);
991    ///
992    /// let (ln, o) = Float::ln_rational_prec_round(Rational::from_unsigneds(3u8, 5), 20, Nearest);
993    /// assert_eq!(ln.to_string(), "-0.510825");
994    /// assert_eq!(o, Greater);
995    /// ```
996    #[allow(clippy::needless_pass_by_value)]
997    #[inline]
998    pub fn ln_rational_prec_round(x: Rational, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
999        Self::ln_rational_prec_round_ref(&x, prec, rm)
1000    }
1001
1002    /// Computes the natural logarithm of a [`Rational`], rounding the result to the specified
1003    /// precision and with the specified rounding mode and returning the result as a [`Float`]. The
1004    /// [`Rational`] is taken by reference. An [`Ordering`] is also returned, indicating whether the
1005    /// rounded logarithm is less than, equal to, or greater than the exact logarithm. Although
1006    /// `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN` it also
1007    /// returns `Equal`.
1008    ///
1009    /// The logarithm of any nonzero negative number is `NaN`.
1010    ///
1011    /// See [`RoundingMode`] for a description of the possible rounding modes.
1012    ///
1013    /// $$
1014    /// f(x,p,m) = \ln{x}+\varepsilon.
1015    /// $$
1016    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1017    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
1018    ///   2^{\lfloor\log_2 |\ln{x}|\rfloor-p+1}$.
1019    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
1020    ///   2^{\lfloor\log_2 |\ln{x}|\rfloor-p}$.
1021    ///
1022    /// If the output has a precision, it is `prec`.
1023    ///
1024    /// Special cases:
1025    /// - $f(0.0,p,m)=-\infty$
1026    ///
1027    /// Neither overflow nor underflow is possible.
1028    ///
1029    /// If you know you'll be using `Nearest`, consider using [`Float::ln_rational_prec_ref`]
1030    /// instead.
1031    ///
1032    /// # Worst-case complexity
1033    /// $T(n) = O(n (\log n)^2 \log\log n)$
1034    ///
1035    /// $M(n) = O(n (\log n)^2)$
1036    ///
1037    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
1038    ///
1039    /// # Panics
1040    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the given
1041    /// precision.
1042    ///
1043    /// # Examples
1044    /// ```
1045    /// use malachite_base::rounding_modes::RoundingMode::*;
1046    /// use malachite_float::Float;
1047    /// use malachite_q::Rational;
1048    /// use std::cmp::Ordering::*;
1049    ///
1050    /// let (ln, o) =
1051    ///     Float::ln_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 5, Floor);
1052    /// assert_eq!(ln.to_string(), "-0.53");
1053    /// assert_eq!(o, Less);
1054    ///
1055    /// let (ln, o) =
1056    ///     Float::ln_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 5, Ceiling);
1057    /// assert_eq!(ln.to_string(), "-0.5");
1058    /// assert_eq!(o, Greater);
1059    ///
1060    /// let (ln, o) =
1061    ///     Float::ln_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 5, Nearest);
1062    /// assert_eq!(ln.to_string(), "-0.5");
1063    /// assert_eq!(o, Greater);
1064    ///
1065    /// let (ln, o) =
1066    ///     Float::ln_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 20, Floor);
1067    /// assert_eq!(ln.to_string(), "-0.510826");
1068    /// assert_eq!(o, Less);
1069    ///
1070    /// let (ln, o) =
1071    ///     Float::ln_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 20, Ceiling);
1072    /// assert_eq!(ln.to_string(), "-0.510825");
1073    /// assert_eq!(o, Greater);
1074    ///
1075    /// let (ln, o) =
1076    ///     Float::ln_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 20, Nearest);
1077    /// assert_eq!(ln.to_string(), "-0.510825");
1078    /// assert_eq!(o, Greater);
1079    /// ```
1080    pub fn ln_rational_prec_round_ref(
1081        x: &Rational,
1082        prec: u64,
1083        rm: RoundingMode,
1084    ) -> (Self, Ordering) {
1085        assert_ne!(prec, 0);
1086        match x.sign() {
1087            Equal => return (float_negative_infinity!(), Equal),
1088            Less => return (float_nan!(), Equal),
1089            Greater => {}
1090        }
1091        if *x == 1u32 {
1092            return (float_zero!(), Equal);
1093        }
1094        assert_ne!(rm, Exact, "Inexact ln");
1095        let x_exp = i32::saturating_from(x.floor_log_base_2_abs()).saturating_add(1);
1096        if x_exp >= Self::MAX_EXPONENT - 1 || x_exp <= Self::MIN_EXPONENT + 1 {
1097            ln_rational_helper_extended(x, prec, rm)
1098        } else {
1099            ln_rational_helper(x, prec, rm)
1100        }
1101    }
1102
1103    /// Computes the natural logarithm of a [`Rational`], rounding the result to the nearest value
1104    /// of the specified precision and returning the result as a [`Float`]. The [`Rational`] is
1105    /// taken by value. An [`Ordering`] is also returned, indicating whether the rounded logarithm
1106    /// is less than, equal to, or greater than the exact logarithm. Although `NaN`s are not
1107    /// comparable to any [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
1108    ///
1109    /// The logarithm of any nonzero negative number is `NaN`.
1110    ///
1111    /// If the logarithm is equidistant from two [`Float`]s with the specified precision, the
1112    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
1113    /// description of the `Nearest` rounding mode.
1114    ///
1115    /// $$
1116    /// f(x,p) = \ln{x}+\varepsilon.
1117    /// $$
1118    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1119    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
1120    ///   |\ln{x}|\rfloor-p}$.
1121    ///
1122    /// If the output has a precision, it is `prec`.
1123    ///
1124    /// Special cases:
1125    /// - $f(0.0,p)=-\infty$
1126    ///
1127    /// Neither overflow nor underflow is possible.
1128    ///
1129    /// If you want to use a rounding mode other than `Nearest`, consider using
1130    /// [`Float::ln_rational_prec_round`] instead.
1131    ///
1132    /// # Worst-case complexity
1133    /// $T(n) = O(n (\log n)^2 \log\log n)$
1134    ///
1135    /// $M(n) = O(n (\log n)^2)$
1136    ///
1137    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
1138    ///
1139    /// # Examples
1140    /// ```
1141    /// use malachite_float::Float;
1142    /// use malachite_q::Rational;
1143    /// use std::cmp::Ordering::*;
1144    ///
1145    /// let (ln, o) = Float::ln_rational_prec(Rational::from_unsigneds(3u8, 5), 5);
1146    /// assert_eq!(ln.to_string(), "-0.5");
1147    /// assert_eq!(o, Greater);
1148    ///
1149    /// let (ln, o) = Float::ln_rational_prec(Rational::from_unsigneds(3u8, 5), 20);
1150    /// assert_eq!(ln.to_string(), "-0.510825");
1151    /// assert_eq!(o, Greater);
1152    /// ```
1153    #[inline]
1154    pub fn ln_rational_prec(x: Rational, prec: u64) -> (Self, Ordering) {
1155        Self::ln_rational_prec_round(x, prec, Nearest)
1156    }
1157
1158    /// Computes the natural logarithm of a [`Rational`], rounding the result to the nearest value
1159    /// of the specified precision and returning the result as a [`Float`]. The [`Rational`] is
1160    /// taken by reference. An [`Ordering`] is also returned, indicating whether the rounded
1161    /// logarithm is less than, equal to, or greater than the exact logarithm. Although `NaN`s are
1162    /// not comparable to any [`Float`], whenever this function returns a `NaN` it also returns
1163    /// `Equal`.
1164    ///
1165    /// The logarithm of any nonzero negative number is `NaN`.
1166    ///
1167    /// If the logarithm is equidistant from two [`Float`]s with the specified precision, the
1168    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
1169    /// description of the `Nearest` rounding mode.
1170    ///
1171    /// $$
1172    /// f(x,p) = \ln{x}+\varepsilon.
1173    /// $$
1174    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1175    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
1176    ///   |\ln{x}|\rfloor-p}$.
1177    ///
1178    /// If the output has a precision, it is `prec`.
1179    ///
1180    /// Special cases:
1181    /// - $f(0.0,p)=-\infty$
1182    ///
1183    /// Neither overflow nor underflow is possible.
1184    ///
1185    /// If you want to use a rounding mode other than `Nearest`, consider using
1186    /// [`Float::ln_rational_prec_round_ref`] instead.
1187    ///
1188    /// # Worst-case complexity
1189    /// $T(n) = O(n (\log n)^2 \log\log n)$
1190    ///
1191    /// $M(n) = O(n (\log n)^2)$
1192    ///
1193    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
1194    ///
1195    /// # Examples
1196    /// ```
1197    /// use malachite_float::Float;
1198    /// use malachite_q::Rational;
1199    /// use std::cmp::Ordering::*;
1200    ///
1201    /// let (ln, o) = Float::ln_rational_prec_ref(&Rational::from_unsigneds(3u8, 5), 5);
1202    /// assert_eq!(ln.to_string(), "-0.5");
1203    /// assert_eq!(o, Greater);
1204    ///
1205    /// let (ln, o) = Float::ln_rational_prec_ref(&Rational::from_unsigneds(3u8, 5), 20);
1206    /// assert_eq!(ln.to_string(), "-0.510825");
1207    /// assert_eq!(o, Greater);
1208    /// ```
1209    #[inline]
1210    pub fn ln_rational_prec_ref(x: &Rational, prec: u64) -> (Self, Ordering) {
1211        Self::ln_rational_prec_round_ref(x, prec, Nearest)
1212    }
1213}
1214
1215impl Ln for Float {
1216    type Output = Self;
1217
1218    /// Computes the natural logarithm of a [`Float`], taking it by value.
1219    ///
1220    /// If the output has a precision, it is the precision of the input. If the logarithm is
1221    /// equidistant from two [`Float`]s with the specified precision, the [`Float`] with fewer 1s in
1222    /// its binary expansion is chosen. See [`RoundingMode`] for a description of the `Nearest`
1223    /// rounding mode.
1224    ///
1225    /// The logarithm of any nonzero negative number is `NaN`.
1226    ///
1227    /// $$
1228    /// f(x) = \ln{x}+\varepsilon.
1229    /// $$
1230    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1231    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
1232    ///   \ln{x}\rfloor-p}$, where $p$ is the maximum precision of the inputs.
1233    ///
1234    /// Special cases:
1235    /// - $f(\text{NaN})=\text{NaN}$
1236    /// - $f(\infty)=\infty$
1237    /// - $f(-\infty)=\text{NaN}$
1238    /// - $f(\pm0.0)=-\infty$
1239    ///
1240    /// Neither overflow nor underflow is possible.
1241    ///
1242    /// If you want to use a rounding mode other than `Nearest`, consider using [`Float::ln_prec`]
1243    /// instead. If you want to specify the output precision, consider using [`Float::ln_round`]. If
1244    /// you want both of these things, consider using [`Float::ln_prec_round`].
1245    ///
1246    /// # Worst-case complexity
1247    /// $T(n) = O(n (\log n)^2 \log\log n)$
1248    ///
1249    /// $M(n) = O(n (\log n)^2)$
1250    ///
1251    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.get_prec()`.
1252    ///
1253    /// # Examples
1254    /// ```
1255    /// use malachite_base::num::arithmetic::traits::Ln;
1256    /// use malachite_base::num::basic::traits::{Infinity, NaN, NegativeInfinity};
1257    /// use malachite_float::Float;
1258    ///
1259    /// assert!(Float::NAN.ln().is_nan());
1260    /// assert_eq!(Float::INFINITY.ln(), Float::INFINITY);
1261    /// assert!(Float::NEGATIVE_INFINITY.ln().is_nan());
1262    /// assert_eq!(
1263    ///     Float::from_unsigned_prec(10u32, 100).0.ln().to_string(),
1264    ///     "2.302585092994045684017991454684"
1265    /// );
1266    /// assert!(Float::from_signed_prec(-10, 100).0.ln().is_nan());
1267    /// ```
1268    #[inline]
1269    fn ln(self) -> Self {
1270        let prec = self.significant_bits();
1271        self.ln_prec_round(prec, Nearest).0
1272    }
1273}
1274
1275impl Ln for &Float {
1276    type Output = Float;
1277
1278    /// Computes the natural logarithm of a [`Float`], taking it by reference.
1279    ///
1280    /// If the output has a precision, it is the precision of the input. If the logarithm is
1281    /// equidistant from two [`Float`]s with the specified precision, the [`Float`] with fewer 1s in
1282    /// its binary expansion is chosen. See [`RoundingMode`] for a description of the `Nearest`
1283    /// rounding mode.
1284    ///
1285    /// The logarithm of any nonzero negative number is `NaN`.
1286    ///
1287    /// $$
1288    /// f(x) = \ln{x}+\varepsilon.
1289    /// $$
1290    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1291    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
1292    ///   \ln{x}\rfloor-p}$, where $p$ is the maximum precision of the inputs.
1293    ///
1294    /// Special cases:
1295    /// - $f(\text{NaN})=\text{NaN}$
1296    /// - $f(\infty)=\infty$
1297    /// - $f(-\infty)=\text{NaN}$
1298    /// - $f(\pm0.0)=-\infty$
1299    ///
1300    /// Neither overflow nor underflow is possible.
1301    ///
1302    /// If you want to use a rounding mode other than `Nearest`, consider using
1303    /// [`Float::ln_prec_ref`] instead. If you want to specify the output precision, consider using
1304    /// [`Float::ln_round_ref`]. If you want both of these things, consider using
1305    /// [`Float::ln_prec_round_ref`].
1306    ///
1307    /// # Worst-case complexity
1308    /// $T(n) = O(n (\log n)^2 \log\log n)$
1309    ///
1310    /// $M(n) = O(n (\log n)^2)$
1311    ///
1312    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.get_prec()`.
1313    ///
1314    /// # Examples
1315    /// ```
1316    /// use malachite_base::num::arithmetic::traits::Ln;
1317    /// use malachite_base::num::basic::traits::{Infinity, NaN, NegativeInfinity};
1318    /// use malachite_float::Float;
1319    ///
1320    /// assert!((&Float::NAN).ln().is_nan());
1321    /// assert_eq!((&Float::INFINITY).ln(), Float::INFINITY);
1322    /// assert!((&Float::NEGATIVE_INFINITY).ln().is_nan());
1323    /// assert_eq!(
1324    ///     (&Float::from_unsigned_prec(10u32, 100).0).ln().to_string(),
1325    ///     "2.302585092994045684017991454684"
1326    /// );
1327    /// assert!((&Float::from_signed_prec(-10, 100).0).ln().is_nan());
1328    /// ```
1329    #[inline]
1330    fn ln(self) -> Float {
1331        let prec = self.significant_bits();
1332        self.ln_prec_round_ref(prec, Nearest).0
1333    }
1334}
1335
1336impl LnAssign for Float {
1337    /// Computes the natural logarithm of a [`Float`] in place.
1338    ///
1339    /// If the output has a precision, it is the precision of the input. If the logarithm is
1340    /// equidistant from two [`Float`]s with the specified precision, the [`Float`] with fewer 1s in
1341    /// its binary expansion is chosen. See [`RoundingMode`] for a description of the `Nearest`
1342    /// rounding mode.
1343    ///
1344    /// The logarithm of any nonzero negative number is `NaN`.
1345    ///
1346    /// $$
1347    /// x\gets = \ln{x}+\varepsilon.
1348    /// $$
1349    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1350    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
1351    ///   \ln{x}\rfloor-p}$, where $p$ is the maximum precision of the inputs.
1352    ///
1353    /// See the [`Float::ln`] documentation for information on special cases, overflow, and
1354    /// underflow.
1355    ///
1356    /// If you want to use a rounding mode other than `Nearest`, consider using
1357    /// [`Float::ln_prec_assign`] instead. If you want to specify the output precision, consider
1358    /// using [`Float::ln_round_assign`]. If you want both of these things, consider using
1359    /// [`Float::ln_prec_round_assign`].
1360    ///
1361    /// # Worst-case complexity
1362    /// $T(n) = O(n (\log n)^2 \log\log n)$
1363    ///
1364    /// $M(n) = O(n (\log n)^2)$
1365    ///
1366    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.get_prec()`.
1367    ///
1368    /// # Examples
1369    /// ```
1370    /// use malachite_base::num::arithmetic::traits::LnAssign;
1371    /// use malachite_base::num::basic::traits::{Infinity, NaN, NegativeInfinity};
1372    /// use malachite_float::Float;
1373    ///
1374    /// let mut x = Float::NAN;
1375    /// x.ln_assign();
1376    /// assert!(x.is_nan());
1377    ///
1378    /// let mut x = Float::INFINITY;
1379    /// x.ln_assign();
1380    /// assert_eq!(x, Float::INFINITY);
1381    ///
1382    /// let mut x = Float::NEGATIVE_INFINITY;
1383    /// x.ln_assign();
1384    /// assert!(x.is_nan());
1385    ///
1386    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
1387    /// x.ln_assign();
1388    /// assert_eq!(x.to_string(), "2.302585092994045684017991454684");
1389    ///
1390    /// let mut x = Float::from_signed_prec(-10, 100).0;
1391    /// x.ln_assign();
1392    /// assert!(x.is_nan());
1393    /// ```
1394    #[inline]
1395    fn ln_assign(&mut self) {
1396        let prec = self.significant_bits();
1397        self.ln_prec_round_assign(prec, Nearest);
1398    }
1399}
1400
1401/// Computes the natural logarithm of a primitive float. Using this function is more accurate than
1402/// using the default `log` function or the one provided by `libm`.
1403///
1404/// The reciprocal logarithm of any nonzero negative number is `NaN`.
1405///
1406/// $$
1407/// f(x) = \ln x+\varepsilon.
1408/// $$
1409/// - If $\ln x$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1410/// - If $\ln x$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2 \ln x\rfloor-p}$,
1411///   where $p$ is precision of the output (typically 24 if `T` is a [`f32`] and 53 if `T` is a
1412///   [`f64`], but less if the output is subnormal).
1413///
1414/// Special cases:
1415/// - $f(\text{NaN})=\text{NaN}$
1416/// - $f(\infty)=\infty$
1417/// - $f(-\infty)=\text{NaN}$
1418/// - $f(\pm0.0)=-\infty$
1419///
1420/// Neither overflow nor underflow is possible.
1421///
1422/// # Worst-case complexity
1423/// Constant time and additional memory.
1424///
1425/// # Examples
1426/// ```
1427/// use malachite_base::num::basic::traits::NegativeInfinity;
1428/// use malachite_base::num::float::NiceFloat;
1429/// use malachite_float::arithmetic::ln::primitive_float_ln;
1430///
1431/// assert!(primitive_float_ln(f32::NAN).is_nan());
1432/// assert_eq!(
1433///     NiceFloat(primitive_float_ln(f32::INFINITY)),
1434///     NiceFloat(f32::INFINITY)
1435/// );
1436/// assert!(primitive_float_ln(f32::NEGATIVE_INFINITY).is_nan());
1437/// assert_eq!(NiceFloat(primitive_float_ln(10.0f32)), NiceFloat(2.3025851));
1438/// assert!(primitive_float_ln(-10.0f32).is_nan());
1439/// ```
1440#[inline]
1441#[allow(clippy::type_repetition_in_bounds)]
1442pub fn primitive_float_ln<T: PrimitiveFloat>(x: T) -> T
1443where
1444    Float: From<T> + PartialOrd<T>,
1445    for<'a> T: ExactFrom<&'a Float> + RoundingFrom<&'a Float>,
1446{
1447    emulate_float_to_float_fn(Float::ln_prec, x)
1448}
1449
1450/// Computes the natural logarithm of a [`Rational`], returning a primitive float result.
1451///
1452/// If the logarithm is equidistant from two primitive floats, the primitive float with fewer 1s in
1453/// its binary expansion is chosen. See [`RoundingMode`] for a description of the `Nearest` rounding
1454/// mode.
1455///
1456/// The logarithm of any negative number is `NaN`.
1457///
1458/// $$
1459/// f(x) = \ln{x}+\varepsilon.
1460/// $$
1461/// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
1462/// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2 |\ln{x}|\rfloor-p}$,
1463///   where $p$ is precision of the output (typically 24 if `T` is a [`f32`] and 53 if `T` is a
1464///   [`f64`], but less if the output is subnormal).
1465///
1466/// Special cases:
1467/// - $f(0)=-\infty$
1468///
1469/// Neither overflow nor underflow is possible.
1470///
1471/// # Worst-case complexity
1472/// Constant time and additional memory.
1473///
1474/// # Examples
1475/// ```
1476/// use malachite_base::num::basic::traits::{NegativeInfinity, Zero};
1477/// use malachite_base::num::float::NiceFloat;
1478/// use malachite_float::arithmetic::ln::primitive_float_ln_rational;
1479/// use malachite_q::Rational;
1480///
1481/// assert_eq!(
1482///     NiceFloat(primitive_float_ln_rational::<f64>(&Rational::ZERO)),
1483///     NiceFloat(f64::NEGATIVE_INFINITY)
1484/// );
1485/// assert_eq!(
1486///     NiceFloat(primitive_float_ln_rational::<f64>(
1487///         &Rational::from_unsigneds(1u8, 3)
1488///     )),
1489///     NiceFloat(-1.0986122886681098)
1490/// );
1491/// assert_eq!(
1492///     NiceFloat(primitive_float_ln_rational::<f64>(&Rational::from(10000))),
1493///     NiceFloat(9.210340371976184)
1494/// );
1495/// assert_eq!(
1496///     NiceFloat(primitive_float_ln_rational::<f64>(&Rational::from(-10000))),
1497///     NiceFloat(f64::NAN)
1498/// );
1499/// ```
1500#[inline]
1501#[allow(clippy::type_repetition_in_bounds)]
1502pub fn primitive_float_ln_rational<T: PrimitiveFloat>(x: &Rational) -> T
1503where
1504    Float: PartialOrd<T>,
1505    for<'a> T: ExactFrom<&'a Float> + RoundingFrom<&'a Float>,
1506{
1507    emulate_rational_to_float_fn(Float::ln_rational_prec_ref, x)
1508}