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