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