Skip to main content

malachite_float/float/arithmetic/
atan.rs

1// Copyright © 2026 Mikhail Hogrefe
2//
3// Uses code adopted from the GNU MPFR Library.
4//
5//      Copyright © 2001-2025 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
15// Port of MPFR's arctangent (`mpfr_atan`, `atan.c`). An input above 1 in magnitude is inverted and
16// its arctangent taken from pi/2. The argument is then reduced by atan(x) = 2 atan((sqrt(1 + x^2)
17// - 1)/x) until it is below about 1/sqrt(prec), and what remains is split into binary chunks, each
18// of whose arctangent is summed by binary splitting of the series for atan(x)/x (with a table of
19// the twenty most common small chunks for low precisions), the pieces being combined through
20// atan(a) + atan(b) = atan((a + b)/(1 - ab)). The arctangent is bounded, so it never overflows; it
21// underflows only for an input at the very bottom of the exponent range, where it is the input
22// itself rounded toward zero, which MPFR's small-input shortcut decides directly.
23
24use crate::InnerFloat::{Finite, Infinity, NaN, Zero};
25use crate::float::arithmetic::round_near_x::{
26    LEADING_TERM_MIN_EXPONENT, round_from_above, small_input_shortcut, value_is_tie,
27};
28use crate::float::arithmetic::sin::{
29    SCALE, SCALED_INPUT_EXPONENT, UNDERFLOW_EXPONENT, scaled_underflow, underflowed,
30};
31use crate::float::arithmetic::tan::round_bracket_signed_by;
32use crate::{Float, emulate_float_to_float_fn, emulate_rational_to_float_fn};
33use alloc::vec;
34use core::cmp::Ordering::{self, Equal, Greater};
35
36use core::mem::take;
37use malachite_base::num::arithmetic::traits::{
38    Abs, Atan, AtanAssign, CeilingLogBase2, IsPowerOf2, Parity, PowerOf2, Reciprocal, Square,
39    SquareAssign,
40};
41use malachite_base::num::basic::floats::PrimitiveFloat;
42use malachite_base::num::basic::integers::PrimitiveInt;
43use malachite_base::num::basic::traits::{
44    NaN as NaNTrait, NegativeZero as NegativeZeroTrait, One, Zero as ZeroTrait,
45};
46use malachite_base::num::conversion::traits::{ExactFrom, RoundingFrom};
47use malachite_base::num::logic::traits::SignificantBits;
48use malachite_base::rounding_modes::RoundingMode::{self, Down, Exact, Floor, Nearest, Up};
49use malachite_base::split_into_chunks_mut;
50use malachite_nz::integer::Integer;
51use malachite_nz::natural::Natural;
52use malachite_nz::natural::arithmetic::float::round::float_can_round;
53use malachite_nz::platform::Limb;
54use malachite_q::Rational;
55
56// For each pair (r, p), a 192-bit truncation of atan(x)/x for x = p/2^r, as three 64-bit words with
57// the lowest first; these are the chunks that a precision of at most 192 bits meets most often, and
58// that are the most expensive to sum. MPFR only compiles this table for 64-bit limbs; the values do
59// not depend on the limb width, so it is used unconditionally here.
60//
61// In Sage: for p in range(1, 2^ceil(r/2)), with x = p/2^r, the words are floor(2^192*n(atan(x)/x,
62// 300)).digits(2^64).
63const ATAN_TABLE: [[u64; 3]; 20] = [
64    [0x6e141587261cdf00, 0x6fe445ecbc3a8d03, 0xed63382b0dda7b45], // (1,1)
65    [0xaa7fa90388b3836b, 0x6dc79ef5f7a217e5, 0xfadbafc96406eb15], // (2,1)
66    [0x319c12cf59d4b2dc, 0xcb2792dc0e2e0d51, 0xffaaddb967ef4e36], // (4,1)
67    [0x8b3957d95d9ad922, 0xc897989f3e888ef7, 0xfeadd4d5617b6e32], // (4,2)
68    [0xc4e6abc8af62e439, 0x4eb9bf602625f0b4, 0xfd0fcdd343cac19b], // (4,3)
69    [0x7c18baeb9bc95789, 0xb12afb6b6d4f7e16, 0xffffaaaaddddb94b], // (8,1)
70    [0x6856a0171a2f001a, 0x62351fbbe60af47, 0xfffeaaadddd4b968],  // (8,2)
71    [0x69164c094f49da06, 0xd517294f7373d07a, 0xfffd001032cb1179], // (8,3)
72    [0x20ef65c10deef460, 0xe78c564015f76048, 0xfffaaadddb94d5bb], // (8,4)
73    [0x3ce233aa002f0344, 0x9dd8ea342a65d4cc, 0xfff7ab27a1f32f95], // (8,5)
74    [0xa37f403c7279c5cb, 0x13ab53a1c8db8497, 0xfff40103192ce74d], // (8,6)
75    [0xe5a85657103c1aa8, 0xb8409e6c914191d3, 0xffefac8a9c40a26b], // (8,7)
76    [0x806d0294c0db8816, 0x779d776dda8c6213, 0xffeaaddd4bb12542], // (8,8)
77    [0x5545d1914ef21478, 0x3aea58d6660f5a12, 0xffe5051f0aebf73a], // (8,9)
78    [0x6e47a91d015f4133, 0xc085ab6b490b7f02, 0xffdeb2787d4adac1], // (8,10)
79    [0x4efc1f931f7ec9b3, 0xb7f43cd16195ef4b, 0xffd7b61702b09aad], // (8,11)
80    [0xd27d1dbf55fed60d, 0xd812c11d7d473e5e, 0xffd0102cb3c1bfbe], // (8,12)
81    [0xca629e927383fe97, 0x8c61aedf58e42206, 0xffc7c0f05db9d1b6], // (8,13)
82    [0x4eff0b53d4e905b7, 0x28ac1e800ca31e9d, 0xffbec89d7dddd7e9], // (8,14)
83    [0xb0a7931deec6fe60, 0xb46feea78588554b, 0xffb527743c8cdd8f], // (8,15)
84];
85
86// A table entry, in [1/2, 1), truncated to `prec` bits.
87//
88// This is `set_table` from atan.c, MPFR 4.2.2.
89fn set_table(prec: u64, x: &[u64; 3]) -> Float {
90    let n = (Natural::from(x[2]) << 128u32) | (Natural::from(x[1]) << 64u32) | Natural::from(x[0]);
91    Float::from_rational_prec_round(Rational::from(n) >> 192u32, prec, Down).0
92}
93
94// Multiplies `xs[k - 1]` by `xs[k]` in place.
95fn mul_prev(xs: &mut [Integer], k: usize) {
96    let (lo, hi) = xs.split_at_mut(k);
97    lo[k - 1] *= &hi[0];
98}
99
100// If x = p/2^r, computes an approximation to atan(x)/x using 2^m terms of the series, with an error
101// of at most 1 ulp at precision `precy`. Assumes 0 < x < 1, so 1 <= p < 2^r. More precisely, p
102// consists of the floor(r/2) bits of the binary expansion of a number 0 < s < 1: the bit of weight
103// 2^-1 is for r = 1, so p <= 1; the bit of weight 2^-2 is for r = 2, so p <= 1; the two bits of
104// weight 2^-3 and 2^-4 are for r = 4, so p <= 3; and in general p < 2^(r/2).
105//
106// With X = x^2 = p/2^r the series is 1 - X/3 + X^2/5 - ... + (-1)^k X^k/(2k+1) + ..., summed by
107// binary splitting: P(a,b) = p if a+1 = b, else P(a,c) P(c,b); Q(a,b) = (2a+1) 2^r if a+1 = b
108// (except Q(0,1) = 1), else Q(a,c) Q(c,b); S(a,b) = p (2a+1) if a+1 = b, else Q(c,b) S(a,c) +
109// Q(a,c) P(a,c) S(c,b). Then atan(x)/x ~ S(0,i)/Q(0,i) for an i making (p/2^r)^i/i small enough.
110// The factor 2^(r(b-a)) in Q(a,b) is implicit, and is applied when Q is used.
111//
112// This is `mpfr_atan_aux` from atan.c, MPFR 4.2.2.
113fn atan_aux(mut p: Integer, mut r: u64, m: usize, precy: u64) -> Float {
114    debug_assert!(p > 0u32);
115    debug_assert!(m > 0);
116    // tabulate values for small precision and small r, which are the most expensive to compute
117    if precy <= 192 {
118        let index = match r {
119            // p has 1 bit: necessarily p = 1
120            1 => Some(0),
121            2 => Some(1),
122            // p has at most 2 bits: 1 <= p <= 3
123            4 => Some(1 + usize::exact_from(&p)),
124            // p has at most 4 bits: 1 <= p <= 15
125            8 => Some(4 + usize::exact_from(&p)),
126            _ => None,
127        };
128        if let Some(index) = index {
129            return set_table(precy, &ATAN_TABLE[index]);
130        }
131    }
132    // From p to p^2, and r to 2r
133    p.square_assign();
134    r <<= 1;
135    // Normalize p
136    let n = p.trailing_zeros().unwrap();
137    if n > 0 {
138        p >>= n;
139        r -= n;
140    }
141    // Since |p/2^r| < 1, and p is a nonzero integer, necessarily r > 0.
142    debug_assert!(r > 0);
143    // MPFR lays the three tables out in one array of 3(m+1) entries; the p = 1 loop can run one
144    // step past 2^m terms, so S and Q get a spare slot each here
145    let len = m + 2;
146    let mut scratch = vec![Integer::ZERO; (len << 1) + m + 1];
147    // ptoj[j] = p^(2^j)
148    split_into_chunks_mut!(scratch, len, [s, q], ptoj);
149    let mut log2_nb_terms = vec![0u64; len + 1];
150    // accu[k] = mult[0] + ... + mult[k], where mult[j] is the number of bits of the corresponding
151    // term S[j]/Q[j]
152    let mut accu = vec![0i64; len + 1];
153    let ri = i64::exact_from(r);
154    let mut i = 0u64;
155    let mut k = 0usize;
156    let p_is_1 = p == 1u32;
157    if p_is_1 {
158        // special case p = 1: the i-th term being X^i/(2i+1) with X = 1/2^r, we can stop when r i >
159        // precy, i.e. i > precy/r
160        let mut n = u64::power_of_2(u64::exact_from(m));
161        if precy / r <= n {
162            n = precy / r + 1;
163        }
164        while i < n {
165            q[k + 1] = Integer::from((i << 1) + 3);
166            s[k] = (&q[k + 1] << r) - Integer::from((i << 1) + 1);
167            q[k] = &q[k + 1] * Integer::from((i << 1) + 1);
168            log2_nb_terms[k] = 1; // S[k]/Q[k] corresponds to 2 terms
169            let mut j = (i + 2) >> 1;
170            let mut l = 1u64;
171            while j.even() {
172                debug_assert!(k > 0);
173                s[k] *= &q[k - 1];
174                let mut t = &s[k - 1] * &q[k];
175                t <<= r << l;
176                t += &s[k];
177                s[k - 1] = t;
178                mul_prev(q, k);
179                log2_nb_terms[k - 1] = l + 1;
180                l += 1;
181                j >>= 1;
182                k -= 1;
183            }
184            i += 2;
185            k += 1;
186        }
187    } else {
188        // p != 1: precompute the ptoj table
189        ptoj[0] = p.clone();
190        for im in 1..=m {
191            ptoj[im] = (&ptoj[im - 1]).square();
192        }
193        // main loop: the i-th term being X^i/(2i+1) with X = p/2^r, we can stop when p^i/2^(ri) <
194        // 2^-precy, i.e. r i > precy + log2(p^i)
195        let n = u64::power_of_2(u64::exact_from(m));
196        let mut done = false;
197        while i < n && !done {
198            // initialize both S[k], Q[k] and S[k+1], Q[k+1]
199            q[k + 1] = Integer::from((i << 1) + 3); // Q(i+1,i+2)
200            s[k + 1] = &p * Integer::from((i << 1) + 1); // S(i+1,i+2)
201            s[k] = (&q[k + 1] << r) - &s[k + 1]; // S(i,i+2)
202            q[k] = &q[k + 1] * Integer::from((i << 1) + 1); // Q(i,i+2)
203            log2_nb_terms[k] = 1; // S[k]/Q[k] corresponds to 2 terms
204            let mut j = (i + 2) >> 1;
205            let mut l = 1u64;
206            while j.even() {
207                // invariant: S[k-1]/Q[k-1] and S[k]/Q[k] correspond to 2^l terms each; combine them
208                // into S[k-1]/Q[k-1]
209                debug_assert!(k > 0);
210                s[k] *= &q[k - 1];
211                s[k] *= &ptoj[usize::exact_from(l)];
212                let mut t = &s[k - 1] * &q[k];
213                t <<= r << l;
214                t += &s[k];
215                s[k - 1] = t;
216                mul_prev(q, k);
217                log2_nb_terms[k - 1] = l + 1;
218                // now S[k-1]/Q[k-1] corresponds to 2^(l+1) terms
219                let mult = (ri << (l + 1))
220                    - i64::exact_from(ptoj[usize::exact_from(l + 1)].significant_bits())
221                    - 1;
222                accu[k - 1] = if k == 1 { mult } else { accu[k - 2] + mult };
223                if accu[k - 1] > i64::exact_from(precy) {
224                    done = true;
225                }
226                l += 1;
227                j >>= 1;
228                k -= 1;
229            }
230            i += 2;
231            k += 1;
232        }
233    }
234    // we need to combine S[0]/Q[0] ... S[k-1]/Q[k-1]
235    let mut h = 0u64; // number of terms accumulated in S[k]/Q[k]
236    while k > 1 {
237        k -= 1;
238        // combine S[k-1]/Q[k-1] and S[k]/Q[k]
239        s[k] *= &q[k - 1];
240        if !p_is_1 {
241            s[k] *= &ptoj[usize::exact_from(log2_nb_terms[k - 1])];
242        }
243        let mut t = &s[k - 1] * &q[k];
244        h += u64::power_of_2(log2_nb_terms[k]);
245        t <<= r * h;
246        t += &s[k];
247        s[k - 1] = t;
248        mul_prev(q, k);
249    }
250    let mut s0 = take(&mut s[0]);
251    let mut q0 = take(&mut q[0]);
252    let precy_i = i64::exact_from(precy);
253    let mut diff = i64::exact_from(s0.significant_bits()) - (precy_i << 1);
254    let mut expo = diff;
255    // a negative shift is a left shift, covering MPFR's mul_2exp branch
256    s0 >>= diff;
257    diff = i64::exact_from(q0.significant_bits()) - precy_i;
258    expo -= diff;
259    q0 >>= diff;
260    s0 /= q0; // truncating division (both positive)
261    // y = (S[0] rounded down to precy) * 2^(expo - r(i-1)); MPFR sets the mantissa via set_z then
262    // overrides the exponent, which is exactly this scaling. The scaled value is atan(x)/x, of
263    // ordinary size, so attaching the scaling before the conversion keeps every exponent in range.
264    Float::from_rational_prec_round(
265        Rational::from(s0) << (expo - ri * (i64::exact_from(i) - 1)),
266        precy,
267        Floor,
268    )
269    .0
270}
271
272// atan x for a tiny nonzero `Rational` x, bracketed by consecutive partial sums of its alternating
273// series: x - x^3/3 < atan x < x - x^3/3 + x^5/5 < x, and so on, a bracket that narrows without
274// bound; the arctangent is transcendental, so it eventually rounds unambiguously. This is the
275// fallback for the tiny inputs that MPFR's small-input shortcut declines, which are those at the
276// very bottom of the exponent range whose result underflows; the general algorithm would otherwise
277// work at a precision of about 2^30 bits for them.
278fn atan_series(x: &Rational, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
279    let negative = *x < 0u32;
280    let ax = x.abs();
281    let x2 = (&ax).square();
282    // hi and lo are the partial sums with an odd and an even number of terms
283    let mut term = ax.clone();
284    let mut hi = ax;
285    let mut lo = Rational::ZERO;
286    let mut k = 1u64;
287    loop {
288        term *= &x2;
289        let t = &term / Rational::from((k << 1) + 1);
290        if k.odd() {
291            lo = &hi - t;
292        } else {
293            hi = &lo + t;
294        }
295        if let Some(result) = round_bracket_signed_by(negative, lo.clone(), hi.clone(), prec, rm) {
296            return result;
297        }
298        k += 1;
299    }
300}
301
302// One step of `atan_rational_huge`: pi to w bits gives pi/2 to within 2^(1 - w), and [lo, hi]
303// brackets atan(1/|x|), so pi/2 - atan(1/|x|) lies between the two ends below.
304fn atan_huge_step(
305    negative: bool,
306    lo: &Rational,
307    hi: &Rational,
308    w: u64,
309    prec: u64,
310    rm: RoundingMode,
311) -> Option<(Float, Ordering)> {
312    // pi_lo <= pi <= pi_lo + 2^(2 - w)
313    let pi_lo = Rational::exact_from(&Float::pi_prec_round(w, Floor).0);
314    let pi_hi = &pi_lo + Rational::power_of_2(2 - i64::exact_from(w));
315    round_bracket_signed_by(
316        negative,
317        (pi_lo >> 1u32) - hi,
318        (pi_hi >> 1u32) - lo,
319        prec,
320        rm,
321    )
322}
323
324// atan x for a `Rational` x beyond the top of the exponent range, where neither x nor 1/x is a
325// `Float`: atan x = pi/2 - atan(1/x), and atan(1/x) is bracketed by the partial sums of its
326// alternating series, so pi/2 minus that bracket settles the result.
327fn atan_rational_huge(x: &Rational, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
328    let negative = *x < 0u32;
329    // 0 < t < 2^(-2^30)
330    let t = x.abs().reciprocal();
331    let mut lo = Rational::ZERO;
332    let mut hi = t.clone();
333    let mut w = prec + 64;
334    // The first bracket, atan(t) in (0, t), is already far narrower than an ulp of pi/2 for a t
335    // this small, and needs none of the powers of t, each of which is as long as the input itself.
336    if let Some(result) = atan_huge_step(negative, &lo, &hi, w, prec, rm) {
337        return result;
338    }
339    let t2 = (&t).square();
340    let mut term = t;
341    let mut k = 1u64;
342    loop {
343        w <<= 1;
344        term *= &t2;
345        let d = &term / Rational::from((k << 1) + 1);
346        if k.odd() {
347            lo = &hi - d;
348        } else {
349            hi = &lo + d;
350        }
351        if let Some(result) = atan_huge_step(negative, &lo, &hi, w, prec, rm) {
352            return result;
353        }
354        k += 1;
355    }
356}
357
358// Computes atan(x) for a nonzero `Rational` x, rounded to precision `prec` with rounding mode `rm`.
359// (x = 0 is handled by the caller.) The result is never exactly representable, so `rm` must not be
360// `Exact`.
361//
362// The general case rounds the input once and takes its `Float` arctangent at a working precision.
363// That is sound because the arctangent is 1-Lipschitz, so the half-ulp of the input carries to the
364// result unmagnified, and because the result is never much smaller than the input: |atan t| > |t|/2
365// for |t| <= 1, while for |t| > 1 the result lies in (pi/4, pi/2) and the input error is damped by
366// 1/(1 + t^2). Both errors together stay below 2^(EXP(a) - m + 1). The two ends of the exponent
367// range, where the input itself is not a `Float`, are bracketed instead.
368pub(crate) fn atan_rational_helper(x: &Rational, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
369    assert_ne!(rm, Exact, "Inexact atan");
370    let exp_x = x.floor_log_base_2_abs() + 1; // the MPFR-style exponent of x
371    if exp_x < UNDERFLOW_EXPONENT {
372        // |atan x| < |x| < 2^(MIN_EXPONENT - 2), below half the smallest positive `Float`, so the
373        // result is zero or that `Float` by the rounding mode alone, and no 2^30-bit arithmetic is
374        // needed
375        return underflowed(*x > 0u32, prec, rm);
376    }
377    // atan(x) = x(1 - x^2/3 + ...), so |x| exceeds |atan x| by less than 2^(3 EXP(x) - 1). Once
378    // that is below the distance from x to the nearest (prec + 1)-bit dyadic -- at least 2^(EXP(x)
379    // - prec - 1)/d for a denominator of d, the two coinciding only when x is itself such a dyadic,
380    // the exact and tie cases -- x's own rounding is the answer, nudged toward zero. The series
381    // below would say the same, but its partial sums are formed exactly, and for a tiny x they are
382    // dense `Rational`s of about 2 |EXP(x)| bits: 7 seconds for x = 2^-536870908, against
383    // microseconds here. (`acot_rational` leans on this too, taking the arctangent of a
384    // reciprocal.) Inputs at the bottom of the exponent range are left to the series below: there
385    // the nudge and the tie test would be working with `Float`s that underflow.
386    if exp_x > LEADING_TERM_MIN_EXPONENT
387        && -(exp_x << 1) > i64::exact_from(prec + x.denominator_ref().significant_bits()) + 4
388    {
389        let positive = *x > 0u32;
390        let ax = x.abs();
391        let rm_abs = if positive { rm } else { -rm };
392        let (wide, o_wide) = Float::from_rational_prec_ref(&ax, prec + 1);
393        let tie = rm_abs == Nearest && value_is_tie(&wide, o_wide, prec);
394        let (t, o) = Float::from_rational_prec_round(ax, prec, rm_abs);
395        let (t, o) = round_from_above(t, o, tie, rm_abs);
396        return if positive { (t, o) } else { (-t, o.reverse()) };
397    }
398    // For |x| <= 1/2, |x| - |x|^3/3 <= |atan x| <= |x| - |x|^3/3 + |x|^5/5, a bracket of relative
399    // width below x^4, which decides the rounding once x^4 is below 2^-(prec + 3); a handful of
400    // terms is cheaper than a `Float` arctangent at the working precision.
401    if exp_x < 0 && -(exp_x << 2) > i64::exact_from(prec) + 3 {
402        return atan_series(x, prec, rm);
403    }
404    if exp_x > Float::MAX_EXPONENT_I64 {
405        return atan_rational_huge(x, prec, rm);
406    }
407    let mut m = prec + prec.ceiling_log_base_2() + 8;
408    let mut increment = Limb::WIDTH;
409    loop {
410        let (f, o_f) = Float::from_rational_prec_ref(x, m);
411        if o_f == Equal {
412            // x is exactly representable at m bits, so its arctangent is simply the `Float` one
413            return atan_prec_round_normal_ref(&f, prec, rm);
414        }
415        let a = (&f).atan();
416        if float_can_round(a.significand_ref().unwrap(), m - 2, prec, rm) {
417            return Float::from_float_prec_round(a, prec, rm);
418        }
419        m += increment;
420        increment = m >> 1;
421    }
422}
423
424// This is mpfr_atan from atan.c, MPFR 4.2.2, for a finite nonzero input, with a series bracket for
425// the tiny inputs whose result underflows.
426fn atan_prec_round_normal_ref(x: &Float, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
427    assert_ne!(rm, Exact, "Inexact atan");
428    let exp_x = i64::from(x.get_exponent().unwrap());
429    // atan(x) = x - x^3/3 + x^5/5 ..., so the error is < 2^(3 EXP(x) - 1), and `EXP(x) - (3 EXP(x)
430    // - 1)` = -2 EXP(x) + 1
431    //
432    // MPFR_FAST_COMPUTE_IF_SMALL_INPUT (atan, x, -2 * MPFR_GET_EXP (x), 1, 0, rnd_mode, {});
433    // atan(x) = x - x^3/3 + ..., so the correction is below 2^(3 EXP(x) - 1) and carries the value
434    // toward zero
435    if let Some(result) = small_input_shortcut(x, -(exp_x << 1), 1, false, prec, rm) {
436        return result;
437    }
438    let negative = *x < 0u32;
439    let xp = x.clone().abs();
440    // Other simple case: atan(±1) = ±pi/4
441    let comparison = xp.partial_cmp(&1u32).unwrap();
442    if comparison == Equal {
443        let (pi, o) = Float::pi_prec_round(prec, if negative { -rm } else { rm });
444        // exact
445        let quarter = pi >> 2u32;
446        return if negative {
447            (-quarter, o.reverse())
448        } else {
449            (quarter, o)
450        };
451    }
452    let mut realprec = prec + prec.ceiling_log_base_2() + 4;
453    let mut increment = Limb::WIDTH;
454    // If |x| < 1, we need more precision to be able to round
455    let sup = if exp_x < 0 {
456        u64::exact_from(2 - exp_x)
457    } else {
458        1
459    };
460    loop {
461        // n0 = ceil(log(prec_requested + 2 + 1 + ln(2.4)/ln(2))/log(2))
462        let n0 = (realprec + sup + 3).ceiling_log_base_2();
463        // since realprec >= 4, n0 >= ceil(log2(8)) >= 3, so 3 n0 > 2
464        let mut wp = realprec + sup + 1 + (3 * n0 - 2).ceiling_log_base_2();
465        // The number of lost bits due to argument reduction is 9 - 2 EXP(sk), estimated by 9 + 2
466        // ceil(log2(p)), since we manage that sk < 1/p. Below 100 bits the argument is not reduced.
467        let (log2p, est_lost) = if prec > 100 {
468            let log2p = (wp.ceiling_log_base_2() >> 1) - 3;
469            (log2p, 9 + (log2p << 1))
470        } else {
471            (0, 0)
472        };
473        wp += est_lost;
474        // use atan(xp) = pi/2 - atan(1/xp) for xp > 1; now 0 < sk <= 1
475        let mut sk = if comparison == Greater {
476            xp.reciprocal_prec_ref(wp).0
477        } else {
478            Float::from_float_prec_ref(&xp, wp).0
479        };
480        // Argument reduction: atan(x) = 2 atan((sqrt(1 + x^2) - 1)/x), applied until |sk| <
481        // k/sqrt(p), where p is the target precision. It keeps 0 < sk <= 1, and is applied at least
482        // once when sk = 1, after which sk < 1 (see atan.c for the interval-arithmetic argument).
483        let mut lost = 0u64;
484        let mut red = 0u64;
485        let log2p_i = i64::exact_from(log2p);
486        loop {
487            let exp_sk = i64::from(sk.get_exponent().unwrap());
488            if exp_sk <= -log2p_i {
489                break;
490            }
491            lost = u64::exact_from(9 - (exp_sk << 1));
492            let mut tmp = sk.square_prec_ref(wp).0;
493            tmp.add_prec_assign_ref(&Float::ONE, wp);
494            tmp.sqrt_prec_assign(wp);
495            tmp.sub_prec_assign_ref(&Float::ONE, wp);
496            sk = if red == 0 && comparison == Greater {
497                // use xp = 1/sk
498                tmp.mul_prec_val_ref(&xp, wp).0
499            } else {
500                tmp.div_prec_val_ref(&sk, wp).0
501            };
502            red += 1;
503        }
504        debug_assert!(sk < 1u32);
505        // Assignation
506        let mut arctgt = Float::ZERO;
507        let mut twopoweri = 1u64;
508        for i in 0..n0 {
509            if sk == 0u32 {
510                break;
511            }
512            // trunc(sk 2^twopoweri) as an integer; since the s_k are decreasing (see
513            // algorithms.tex) and s_0 = min(|x|, 1/|x|) < 1, sk < 1
514            let ukz = Integer::rounding_from(&(&sk << twopoweri), Down).0;
515            if ukz != 0u32 {
516                // tmp = ukz / 2^twopoweri
517                let tmp = Float::from_integer_prec_ref(&ukz, wp).0 >> twopoweri;
518                // atan(A_k)
519                let tmp2 = atan_aux(ukz, twopoweri, usize::exact_from(n0 - i), wp)
520                    .mul_prec_val_ref(&tmp, wp)
521                    .0;
522                // Addition
523                arctgt.add_prec_assign(tmp2, wp);
524                // Next iteration
525                let tmp2 = sk.sub_prec_ref_ref(&tmp, wp).0;
526                sk.mul_prec_assign_ref(&tmp, wp);
527                sk.add_prec_assign_ref(&Float::ONE, wp);
528                sk = tmp2.div_prec(sk, wp).0;
529            }
530            twopoweri <<= 1;
531        }
532        // Add the last step: atan(sk) ~= sk
533        arctgt.add_prec_assign(sk, wp);
534        // undo the argument reduction
535        arctgt <<= red;
536        if comparison == Greater {
537            // atan(x) = pi/2 - atan(1/x) for x > 0
538            arctgt = (Float::pi_prec(wp).0 >> 1u32).sub_prec(arctgt, wp).0;
539        }
540        debug_assert!(arctgt > 0u32);
541        let err = i64::exact_from(realprec + est_lost) - i64::exact_from(lost);
542        if err > 0
543            && float_can_round(
544                arctgt.significand_ref().unwrap(),
545                u64::exact_from(err),
546                prec,
547                rm,
548            )
549        {
550            return Float::from_float_prec_round(if negative { -arctgt } else { arctgt }, prec, rm);
551        }
552        realprec += increment;
553        increment = realprec >> 1;
554    }
555}
556
557// u/2^k with the sign of `positive`, rounded to `prec` with `rm`. The shift is exact, so the
558// ternary value is the conversion's, reversed along with the sign.
559pub(crate) fn scaled_unsigned(
560    u: u64,
561    k: u32,
562    positive: bool,
563    prec: u64,
564    rm: RoundingMode,
565) -> (Float, Ordering) {
566    let (f, o) = Float::from_unsigned_prec_round(u, prec, if positive { rm } else { -rm });
567    let f = f >> k;
568    if positive { (f, o) } else { (-f, o.reverse()) }
569}
570
571// Computes atan(x) u/(2 pi) for a finite nonzero `Float` x and a nonzero u, rounded to precision
572// `prec` with rounding mode `rm`. `rm` may be `Exact` only for |x| = 1, where the result is u/8.
573//
574// This is mpfr_atanu from atanu.c, MPFR 4.2.2. The quotient is formed with the numerator scaled up
575// by 2^SCALE, since atan(x) u/(2 pi) can fall below the smallest positive `Float` for a tiny x and
576// a small u, which MPFR, computing inside a temporarily extended exponent range, never sees; a
577// result below it is then decided by the rounding mode alone, as in `sin_with_period`.
578fn atan_with_period_prec_round_normal_ref(
579    x: &Float,
580    u: u64,
581    prec: u64,
582    rm: RoundingMode,
583) -> (Float, Ordering) {
584    let positive = *x > 0u32;
585    let exp_x = i64::from(x.get_exponent().unwrap());
586    // |x| = 1: atanu(1, u) = u/8, atanu(-1, u) = -u/8, both exact
587    if exp_x == 1 && x.significand_ref().unwrap().is_power_of_2() {
588        return scaled_unsigned(u, 3, positive, prec, rm);
589    }
590    // Only |x| = 1 can be rounded exactly
591    assert_ne!(rm, Exact, "Inexact atan_with_period");
592    // For x >= 1, pi/2 - 1/x < atan(x) < pi/2, so u/4 - u/(2 pi x) < atanu(x, u) < u/4, and the
593    // relative difference from u/4 is below 2/(pi x) < 1/x <= 2^(1 - EXP(x)). Once that is at most
594    // 2^(-prec - 2), the difference is at most a quarter ulp of u/4, hence at most half an ulp of
595    // u/4 at the target precision, so the result rounds like the value one ulp below u/4 at a
596    // working precision above the target's. Requiring EXP(x) >= 65 also gives x > 2u/pi, which
597    // keeps that value above (u - 1)/4.
598    if exp_x >= 65 && exp_x > i64::exact_from(prec) + 2 {
599        let w = if prec <= 63 { 65 } else { prec + 2 };
600        // exact, since w >= 64
601        let mut t = Float::from_unsigned_prec_round(u, w, Exact).0;
602        t.decrement();
603        // the last bit of t is 1 and w exceeds the target precision, so t is not representable
604        // there, which pins the ternary value below
605        t >>= 2u32;
606        return Float::from_float_prec_round(if positive { t } else { -t }, prec, rm);
607    }
608    arc_with_period_scale(
609        // scaling by a power of 2 is exact, and atan(x) u 2^SCALE stays far below the top of the
610        // range, since |atan x| < pi/2 and u < 2^64
611        |w| x.atan_prec_round_ref(w, Up).0 << SCALE,
612        u,
613        positive,
614        prec,
615        rm,
616    )
617}
618
619// The Ziv loop shared by the inverse trigonometric functions with a period: given a way to compute
620// f(x) 2^SCALE rounded away from zero at a working precision, forms f(x) u/(2 pi). It is used by
621// the `Float` and `Rational` arctangents and by the arcsine, whose error analyses agree.
622//
623// The numerator is scaled up by 2^SCALE throughout, since f(x) u/(2 pi) can fall below the smallest
624// positive `Float` for a tiny x and a small u, which MPFR, computing inside a temporarily extended
625// exponent range, never sees; a result below it is then decided by the rounding mode alone, as in
626// `sin_with_period`. Scaling before the multiplication rather than after also lets a `Rational` x
627// too small to be a `Float` at all reach the loop, which is why the shift belongs to the caller.
628pub(crate) fn arc_with_period_scale<F: FnMut(u64) -> Float>(
629    mut scaled_f: F,
630    u: u64,
631    positive: bool,
632    prec: u64,
633    rm: RoundingMode,
634) -> (Float, Ordering) {
635    let mut w = prec + prec.ceiling_log_base_2() + 10;
636    let mut increment = Limb::WIDTH;
637    let u_float = Float::from(u);
638    loop {
639        // In the error analysis below, each theta denotes a value with |theta| <= 2^(1 - w).
640        //
641        // t = f(x) 2^SCALE (1 + theta), nonzero since we rounded away from zero and x is not
642        let mut t = scaled_f(w);
643        // t = f(x) u 2^SCALE (1 + theta)^2
644        t.mul_prec_round_assign_ref(&u_float, w, Up);
645        // 2 pi rounded toward zero, so that the quotient rounds away
646        let two_pi = Float::pi_prec_round(w, Down).0 << 1u32;
647        // t = f(x) u 2^SCALE/(2 pi) (1 + theta)^4, whose relative error is below 2^(4 - w) since
648        // |(1 + theta)^4 - 1| <= 8 |theta| for w >= 3
649        t.div_prec_round_assign(two_pi, w, Up);
650        if let Some(result) = scaled_underflow(&t, positive, prec, rm) {
651            return result;
652        }
653        let t = t >> SCALE;
654        if float_can_round(t.significand_ref().unwrap(), w - 4, prec, rm) {
655            return Float::from_float_prec_round(t, prec, rm);
656        }
657        w += increment;
658        increment = w >> 1;
659    }
660}
661
662// Computes atan(x) u/(2 pi) for a nonzero `Rational` x and a nonzero u, rounded to precision `prec`
663// with rounding mode `rm`. (x = 0 and u = 0 are handled by the caller.) `rm` may be `Exact` only
664// for |x| = 1, where the result is u/8.
665//
666// The three branches match the `Float` case, with one addition: an x below the bottom of the
667// exponent range is not a `Float`, but its arctangent is its own leading term, so the quotient is
668// formed from x itself. That substitution neglects a relative x^2/3, which for such an x is below
669// 2^(2 SCALED_INPUT_EXPONENT) and so far beneath any working precision the loop can reach. It is
670// also needed rather than merely cheaper: `atan_rational_helper` reports such an x as an underflow,
671// and a large u can lift the quotient back into the range, where that answer would be wrong.
672pub(crate) fn atan_with_period_rational_helper(
673    x: &Rational,
674    u: u64,
675    prec: u64,
676    rm: RoundingMode,
677) -> (Float, Ordering) {
678    let positive = *x > 0u32;
679    let exp_x = x.floor_log_base_2_abs() + 1; // the MPFR-style exponent of x
680    // |x| = 1: atanu(1, u) = u/8, atanu(-1, u) = -u/8, both exact
681    if exp_x == 1 && x.denominator_ref() == &1u32 {
682        return scaled_unsigned(u, 3, positive, prec, rm);
683    }
684    // Only |x| = 1 can be rounded exactly
685    assert_ne!(rm, Exact, "Inexact atan_with_period_rational");
686    // as in the `Float` case, the result is one ulp below u/4 once x is large enough
687    if exp_x >= 65 && exp_x > i64::exact_from(prec) + 2 {
688        let w = if prec <= 63 { 65 } else { prec + 2 };
689        // exact, since w >= 64
690        let mut t = Float::from_unsigned_prec_round(u, w, Exact).0;
691        t.decrement();
692        t >>= 2u32;
693        return Float::from_float_prec_round(if positive { t } else { -t }, prec, rm);
694    }
695    if exp_x <= SCALED_INPUT_EXPONENT {
696        let scaled = x << SCALE;
697        return arc_with_period_scale(
698            |w| Float::from_rational_prec_round_ref(&scaled, w, Up).0,
699            u,
700            positive,
701            prec,
702            rm,
703        );
704    }
705    arc_with_period_scale(
706        |w| atan_rational_helper(x, w, Up).0 << SCALE,
707        u,
708        positive,
709        prec,
710        rm,
711    )
712}
713
714impl Float {
715    /// Computes $\arctan x$, the arctangent of a [`Float`], rounding the result to the specified
716    /// precision and with the specified rounding mode. The [`Float`] is taken by value. An
717    /// [`Ordering`] is also returned, indicating whether the rounded arctangent is less than, equal
718    /// to, or greater than the exact arctangent. Although `NaN`s are not comparable to any
719    /// [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
720    ///
721    /// See [`RoundingMode`] for a description of the possible rounding modes.
722    ///
723    /// $$
724    /// f(x,p,m) = \arctan x+\varepsilon.
725    /// $$
726    /// - If $x$ is NaN, $\varepsilon$ may be ignored or assumed to be 0.
727    /// - If $x$ is not NaN and $m$ is not `Nearest`, then $|\varepsilon| < 2^{\lfloor\log_2
728    ///   |\arctan x|\rfloor-p+1}$.
729    /// - If $x$ is not NaN and $m$ is `Nearest`, then $|\varepsilon| \leq 2^{\lfloor\log_2 |\arctan
730    ///   x|\rfloor-p}$.
731    ///
732    /// If the output has a precision, it is `prec`.
733    ///
734    /// Special cases:
735    /// - $f(\text{NaN},p,m)=\text{NaN}$
736    /// - $f(\pm\infty,p,m)=\pm\pi/2$, rounded
737    /// - $f(\pm0.0,p,m)=\pm0.0$
738    ///
739    /// Overflow and underflow:
740    /// - Since $|\arctan x| < \pi/2$, the result never overflows.
741    /// - If $0<f(x,p,m)<2^{-2^{30}}$, and $m$ is `Floor` or `Down`, $0.0$ is returned instead.
742    /// - If $0<f(x,p,m)<2^{-2^{30}}$, and $m$ is `Ceiling` or `Up`, $2^{-2^{30}}$ is returned
743    ///   instead.
744    /// - If $0<f(x,p,m)\leq2^{-2^{30}-1}$, and $m$ is `Nearest`, $0.0$ is returned instead.
745    /// - If $2^{-2^{30}-1}<f(x,p,m)<2^{-2^{30}}$, and $m$ is `Nearest`, $2^{-2^{30}}$ is returned
746    ///   instead.
747    /// - If $-2^{-2^{30}}<f(x,p,m)<0$, and $m$ is `Ceiling` or `Down`, $-0.0$ is returned instead.
748    /// - If $-2^{-2^{30}}<f(x,p,m)<0$, and $m$ is `Floor` or `Up`, $-2^{-2^{30}}$ is returned
749    ///   instead.
750    /// - If $-2^{-2^{30}-1}\leq f(x,p,m)<0$, and $m$ is `Nearest`, $-0.0$ is returned instead.
751    /// - If $-2^{-2^{30}}<f(x,p,m)<-2^{-2^{30}-1}$, and $m$ is `Nearest`, $-2^{-2^{30}}$ is
752    ///   returned instead.
753    ///
754    /// Underflow requires an input of magnitude $2^{-2^{30}}$, the smallest positive [`Float`],
755    /// rounded toward zero: since $|\arctan x| < |x|$ for nonzero $x$, no other input can reach it.
756    ///
757    /// If you know you'll be using `Nearest`, consider using [`Float::atan_prec`] instead. If you
758    /// know that your target precision is the precision of the input, consider using
759    /// [`Float::atan_round`] instead. If both of these things are true, consider using
760    /// [`Float::atan`] instead.
761    ///
762    /// # Worst-case complexity
763    /// $T(n, m) = O(n (\log n)^3 \log\log n + (n+m) (\log (n+m))^2 \log\log (n+m))$
764    ///
765    /// $M(n, m) = O((n+m) \log (n+m))$
766    ///
767    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
768    /// `self.significant_bits()`: an input above 1 in magnitude is first inverted, and the argument
769    /// is then halved a logarithmic number of times and split into chunks whose arctangents are
770    /// summed by binary splitting, all at a working precision of about $n$; the summation is the
771    /// first term, and the inversion of the $m$-bit input the second. The magnitude of the input
772    /// does not drive the cost.
773    ///
774    /// # Panics
775    /// Panics if `rm` is `Exact` and `self` is nonzero and not NaN, since the arctangent of a
776    /// finite nonzero [`Float`] is never exactly representable and neither is $\pm\pi/2$, or if
777    /// `prec` is zero.
778    ///
779    /// # Examples
780    /// ```
781    /// use malachite_base::rounding_modes::RoundingMode::*;
782    /// use malachite_float::Float;
783    /// use std::cmp::Ordering::*;
784    ///
785    /// let (c, o) = Float::from_unsigned_prec(1u32, 100)
786    ///     .0
787    ///     .atan_prec_round(5, Floor);
788    /// assert_eq!(c.to_string(), "0.781");
789    /// assert_eq!(o, Less);
790    ///
791    /// let (c, o) = Float::from_unsigned_prec(1u32, 100)
792    ///     .0
793    ///     .atan_prec_round(5, Ceiling);
794    /// assert_eq!(c.to_string(), "0.812");
795    /// assert_eq!(o, Greater);
796    ///
797    /// let (c, o) = Float::from_unsigned_prec(1u32, 100)
798    ///     .0
799    ///     .atan_prec_round(5, Nearest);
800    /// assert_eq!(c.to_string(), "0.781");
801    /// assert_eq!(o, Less);
802    ///
803    /// let (c, o) = Float::from_unsigned_prec(1u32, 100)
804    ///     .0
805    ///     .atan_prec_round(20, Floor);
806    /// assert_eq!(c.to_string(), "0.78539753");
807    /// assert_eq!(o, Less);
808    ///
809    /// let (c, o) = Float::from_unsigned_prec(1u32, 100)
810    ///     .0
811    ///     .atan_prec_round(20, Ceiling);
812    /// assert_eq!(c.to_string(), "0.78539848");
813    /// assert_eq!(o, Greater);
814    ///
815    /// let (c, o) = Float::from_unsigned_prec(1u32, 100)
816    ///     .0
817    ///     .atan_prec_round(20, Nearest);
818    /// assert_eq!(c.to_string(), "0.78539848");
819    /// assert_eq!(o, Greater);
820    /// ```
821    #[inline]
822    pub fn atan_prec_round(self, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
823        self.atan_prec_round_ref(prec, rm)
824    }
825
826    /// Computes $\arctan x$, the arctangent of a [`Float`], rounding the result to the specified
827    /// precision and with the specified rounding mode. The [`Float`] is taken by reference. An
828    /// [`Ordering`] is also returned, indicating whether the rounded arctangent is less than, equal
829    /// to, or greater than the exact arctangent. Although `NaN`s are not comparable to any
830    /// [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
831    ///
832    /// See [`RoundingMode`] for a description of the possible rounding modes.
833    ///
834    /// $$
835    /// f(x,p,m) = \arctan x+\varepsilon.
836    /// $$
837    /// - If $x$ is NaN, $\varepsilon$ may be ignored or assumed to be 0.
838    /// - If $x$ is not NaN and $m$ is not `Nearest`, then $|\varepsilon| < 2^{\lfloor\log_2
839    ///   |\arctan x|\rfloor-p+1}$.
840    /// - If $x$ is not NaN and $m$ is `Nearest`, then $|\varepsilon| \leq 2^{\lfloor\log_2 |\arctan
841    ///   x|\rfloor-p}$.
842    ///
843    /// If the output has a precision, it is `prec`.
844    ///
845    /// Special cases:
846    /// - $f(\text{NaN},p,m)=\text{NaN}$
847    /// - $f(\pm\infty,p,m)=\pm\pi/2$, rounded
848    /// - $f(\pm0.0,p,m)=\pm0.0$
849    ///
850    /// Overflow and underflow:
851    /// - Since $|\arctan x| < \pi/2$, the result never overflows.
852    /// - If $0<f(x,p,m)<2^{-2^{30}}$, and $m$ is `Floor` or `Down`, $0.0$ is returned instead.
853    /// - If $0<f(x,p,m)<2^{-2^{30}}$, and $m$ is `Ceiling` or `Up`, $2^{-2^{30}}$ is returned
854    ///   instead.
855    /// - If $0<f(x,p,m)\leq2^{-2^{30}-1}$, and $m$ is `Nearest`, $0.0$ is returned instead.
856    /// - If $2^{-2^{30}-1}<f(x,p,m)<2^{-2^{30}}$, and $m$ is `Nearest`, $2^{-2^{30}}$ is returned
857    ///   instead.
858    /// - If $-2^{-2^{30}}<f(x,p,m)<0$, and $m$ is `Ceiling` or `Down`, $-0.0$ is returned instead.
859    /// - If $-2^{-2^{30}}<f(x,p,m)<0$, and $m$ is `Floor` or `Up`, $-2^{-2^{30}}$ is returned
860    ///   instead.
861    /// - If $-2^{-2^{30}-1}\leq f(x,p,m)<0$, and $m$ is `Nearest`, $-0.0$ is returned instead.
862    /// - If $-2^{-2^{30}}<f(x,p,m)<-2^{-2^{30}-1}$, and $m$ is `Nearest`, $-2^{-2^{30}}$ is
863    ///   returned instead.
864    ///
865    /// Underflow requires an input of magnitude $2^{-2^{30}}$, the smallest positive [`Float`],
866    /// rounded toward zero: since $|\arctan x| < |x|$ for nonzero $x$, no other input can reach it.
867    ///
868    /// If you know you'll be using `Nearest`, consider using [`Float::atan_prec_ref`] instead. If
869    /// you know that your target precision is the precision of the input, consider using
870    /// [`Float::atan_round_ref`] instead. If both of these things are true, consider using
871    /// `(&Float).atan()` instead.
872    ///
873    /// # Worst-case complexity
874    /// $T(n, m) = O(n (\log n)^3 \log\log n + (n+m) (\log (n+m))^2 \log\log (n+m))$
875    ///
876    /// $M(n, m) = O((n+m) \log (n+m))$
877    ///
878    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
879    /// `self.significant_bits()`: an input above 1 in magnitude is first inverted, and the argument
880    /// is then halved a logarithmic number of times and split into chunks whose arctangents are
881    /// summed by binary splitting, all at a working precision of about $n$; the summation is the
882    /// first term, and the inversion of the $m$-bit input the second. The magnitude of the input
883    /// does not drive the cost.
884    ///
885    /// # Panics
886    /// Panics if `rm` is `Exact` and `self` is nonzero and not NaN, since the arctangent of a
887    /// finite nonzero [`Float`] is never exactly representable and neither is $\pm\pi/2$, or if
888    /// `prec` is zero.
889    ///
890    /// # Examples
891    /// ```
892    /// use malachite_base::rounding_modes::RoundingMode::*;
893    /// use malachite_float::Float;
894    /// use std::cmp::Ordering::*;
895    ///
896    /// let (c, o) = (&Float::from_unsigned_prec(1u32, 100).0).atan_prec_round_ref(5, Floor);
897    /// assert_eq!(c.to_string(), "0.781");
898    /// assert_eq!(o, Less);
899    ///
900    /// let (c, o) = (&Float::from_unsigned_prec(1u32, 100).0).atan_prec_round_ref(5, Ceiling);
901    /// assert_eq!(c.to_string(), "0.812");
902    /// assert_eq!(o, Greater);
903    ///
904    /// let (c, o) = (&Float::from_unsigned_prec(1u32, 100).0).atan_prec_round_ref(5, Nearest);
905    /// assert_eq!(c.to_string(), "0.781");
906    /// assert_eq!(o, Less);
907    ///
908    /// let (c, o) = (&Float::from_unsigned_prec(1u32, 100).0).atan_prec_round_ref(20, Floor);
909    /// assert_eq!(c.to_string(), "0.78539753");
910    /// assert_eq!(o, Less);
911    ///
912    /// let (c, o) = (&Float::from_unsigned_prec(1u32, 100).0).atan_prec_round_ref(20, Ceiling);
913    /// assert_eq!(c.to_string(), "0.78539848");
914    /// assert_eq!(o, Greater);
915    ///
916    /// let (c, o) = (&Float::from_unsigned_prec(1u32, 100).0).atan_prec_round_ref(20, Nearest);
917    /// assert_eq!(c.to_string(), "0.78539848");
918    /// assert_eq!(o, Greater);
919    /// ```
920    pub fn atan_prec_round_ref(&self, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
921        assert_ne!(prec, 0);
922        match &self.0 {
923            NaN => (Self::NAN, Equal),
924            // atan(+infinity) = pi/2, atan(-infinity) = -pi/2
925            Infinity { sign } => {
926                assert_ne!(rm, Exact, "Inexact atan");
927                let (pi, o) = Self::pi_prec_round(prec, if *sign { rm } else { -rm });
928                // exact
929                let half = pi >> 1u32;
930                if *sign {
931                    (half, o)
932                } else {
933                    (-half, o.reverse())
934                }
935            }
936            // atan(+0) = +0, atan(-0) = -0
937            Zero { .. } => (self.clone(), Equal),
938            Finite { .. } => atan_prec_round_normal_ref(self, prec, rm),
939        }
940    }
941
942    /// Computes $\arctan x$, the arctangent of a [`Float`], rounding the result to the nearest
943    /// value of the specified precision. The [`Float`] is taken by value. An [`Ordering`] is also
944    /// returned, indicating whether the rounded arctangent is less than, equal to, or greater than
945    /// the exact arctangent. Although `NaN`s are not comparable to any [`Float`], whenever this
946    /// function returns a `NaN` it also returns `Equal`.
947    ///
948    /// If the arctangent is equidistant from two [`Float`]s with the specified precision, the
949    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
950    /// description of the `Nearest` rounding mode.
951    ///
952    /// $$
953    /// f(x,p) = \arctan x+\varepsilon.
954    /// $$
955    /// - If $x$ is NaN, $\varepsilon$ may be ignored or assumed to be 0.
956    /// - If $x$ is not NaN, then $|\varepsilon| < 2^{\lfloor\log_2 |\arctan x|\rfloor-p}$.
957    ///
958    /// If the output has a precision, it is `prec`.
959    ///
960    /// Special cases:
961    /// - $f(\text{NaN},p)=\text{NaN}$
962    /// - $f(\pm\infty,p)=\pm\pi/2$, rounded
963    /// - $f(\pm0.0,p)=1.0$
964    ///
965    /// Overflow and underflow:
966    /// - Since $|\arctan x| < \pi/2$, the result never overflows.
967    /// - If $0<f(x,p)\leq2^{-2^{30}-1}$, $0.0$ is returned instead.
968    /// - If $2^{-2^{30}-1}<f(x,p)<2^{-2^{30}}$, $2^{-2^{30}}$ is returned instead.
969    /// - If $-2^{-2^{30}-1}\leq f(x,p)<0$, $-0.0$ is returned instead.
970    /// - If $-2^{-2^{30}}<f(x,p)<-2^{-2^{30}-1}$, $-2^{-2^{30}}$ is returned instead.
971    ///
972    /// Underflow requires an input of magnitude $2^{-2^{30}}$, the smallest positive [`Float`],
973    /// rounded toward zero: since $|\arctan x| < |x|$ for nonzero $x$, no other input can reach it.
974    ///
975    /// If you want to use a rounding mode other than `Nearest`, consider using
976    /// [`Float::atan_prec_round`] instead. If you know that your target precision is the precision
977    /// of the input, consider using [`Float::atan`] instead.
978    ///
979    /// # Worst-case complexity
980    /// $T(n, m) = O(n (\log n)^3 \log\log n + (n+m) (\log (n+m))^2 \log\log (n+m))$
981    ///
982    /// $M(n, m) = O((n+m) \log (n+m))$
983    ///
984    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
985    /// `self.significant_bits()`: an input above 1 in magnitude is first inverted, and the argument
986    /// is then halved a logarithmic number of times and split into chunks whose arctangents are
987    /// summed by binary splitting, all at a working precision of about $n$; the summation is the
988    /// first term, and the inversion of the $m$-bit input the second. The magnitude of the input
989    /// does not drive the cost.
990    ///
991    /// # Panics
992    /// Panics if `prec` is zero.
993    ///
994    /// # Examples
995    /// ```
996    /// use malachite_float::Float;
997    /// use std::cmp::Ordering::*;
998    ///
999    /// let (c, o) = Float::from_unsigned_prec(1u32, 100).0.atan_prec(5);
1000    /// assert_eq!(c.to_string(), "0.781");
1001    /// assert_eq!(o, Less);
1002    ///
1003    /// let (c, o) = Float::from_unsigned_prec(1u32, 100).0.atan_prec(20);
1004    /// assert_eq!(c.to_string(), "0.78539848");
1005    /// assert_eq!(o, Greater);
1006    /// ```
1007    #[inline]
1008    pub fn atan_prec(self, prec: u64) -> (Self, Ordering) {
1009        self.atan_prec_round(prec, Nearest)
1010    }
1011
1012    /// Computes $\arctan x$, the arctangent of a [`Float`], rounding the result to the nearest
1013    /// value of the specified precision. The [`Float`] is taken by reference. An [`Ordering`] is
1014    /// also returned, indicating whether the rounded arctangent is less than, equal to, or greater
1015    /// than the exact arctangent. Although `NaN`s are not comparable to any [`Float`], whenever
1016    /// this function returns a `NaN` it also returns `Equal`.
1017    ///
1018    /// If the arctangent is equidistant from two [`Float`]s with the specified precision, the
1019    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
1020    /// description of the `Nearest` rounding mode.
1021    ///
1022    /// $$
1023    /// f(x,p) = \arctan x+\varepsilon.
1024    /// $$
1025    /// - If $x$ is NaN, $\varepsilon$ may be ignored or assumed to be 0.
1026    /// - If $x$ is not NaN, then $|\varepsilon| < 2^{\lfloor\log_2 |\arctan x|\rfloor-p}$.
1027    ///
1028    /// If the output has a precision, it is `prec`.
1029    ///
1030    /// Special cases:
1031    /// - $f(\text{NaN},p)=\text{NaN}$
1032    /// - $f(\pm\infty,p)=\pm\pi/2$, rounded
1033    /// - $f(\pm0.0,p)=1.0$
1034    ///
1035    /// Overflow and underflow:
1036    /// - Since $|\arctan x| < \pi/2$, the result never overflows.
1037    /// - If $0<f(x,p)\leq2^{-2^{30}-1}$, $0.0$ is returned instead.
1038    /// - If $2^{-2^{30}-1}<f(x,p)<2^{-2^{30}}$, $2^{-2^{30}}$ is returned instead.
1039    /// - If $-2^{-2^{30}-1}\leq f(x,p)<0$, $-0.0$ is returned instead.
1040    /// - If $-2^{-2^{30}}<f(x,p)<-2^{-2^{30}-1}$, $-2^{-2^{30}}$ is returned instead.
1041    ///
1042    /// Underflow requires an input of magnitude $2^{-2^{30}}$, the smallest positive [`Float`],
1043    /// rounded toward zero: since $|\arctan x| < |x|$ for nonzero $x$, no other input can reach it.
1044    ///
1045    /// If you want to use a rounding mode other than `Nearest`, consider using
1046    /// [`Float::atan_prec_round_ref`] instead. If you know that your target precision is the
1047    /// precision of the input, consider using `(&Float).atan()` instead.
1048    ///
1049    /// # Worst-case complexity
1050    /// $T(n, m) = O(n (\log n)^3 \log\log n + (n+m) (\log (n+m))^2 \log\log (n+m))$
1051    ///
1052    /// $M(n, m) = O((n+m) \log (n+m))$
1053    ///
1054    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
1055    /// `self.significant_bits()`: an input above 1 in magnitude is first inverted, and the argument
1056    /// is then halved a logarithmic number of times and split into chunks whose arctangents are
1057    /// summed by binary splitting, all at a working precision of about $n$; the summation is the
1058    /// first term, and the inversion of the $m$-bit input the second. The magnitude of the input
1059    /// does not drive the cost.
1060    ///
1061    /// # Panics
1062    /// Panics if `prec` is zero.
1063    ///
1064    /// # Examples
1065    /// ```
1066    /// use malachite_float::Float;
1067    /// use std::cmp::Ordering::*;
1068    ///
1069    /// let (c, o) = (&Float::from_unsigned_prec(1u32, 100).0).atan_prec_ref(5);
1070    /// assert_eq!(c.to_string(), "0.781");
1071    /// assert_eq!(o, Less);
1072    ///
1073    /// let (c, o) = (&Float::from_unsigned_prec(1u32, 100).0).atan_prec_ref(20);
1074    /// assert_eq!(c.to_string(), "0.78539848");
1075    /// assert_eq!(o, Greater);
1076    /// ```
1077    #[inline]
1078    pub fn atan_prec_ref(&self, prec: u64) -> (Self, Ordering) {
1079        self.atan_prec_round_ref(prec, Nearest)
1080    }
1081
1082    /// Computes $\arctan x$, the arctangent of a [`Float`], rounding the result with the specified
1083    /// rounding mode. The [`Float`] is taken by value. An [`Ordering`] is also returned, indicating
1084    /// whether the rounded arctangent is less than, equal to, or greater than the exact arctangent.
1085    /// Although `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN`
1086    /// it also returns `Equal`.
1087    ///
1088    /// The precision of the output is the precision of the input. See [`RoundingMode`] for a
1089    /// description of the possible rounding modes.
1090    ///
1091    /// $$
1092    /// f(x,m) = \arctan x+\varepsilon.
1093    /// $$
1094    /// - If $x$ is NaN, $\varepsilon$ may be ignored or assumed to be 0.
1095    /// - If $x$ is not NaN and $m$ is not `Nearest`, then $|\varepsilon| < 2^{\lfloor\log_2
1096    ///   |\arctan x|\rfloor-p+1}$, where $p$ is the precision of the input.
1097    /// - If $x$ is not NaN and $m$ is `Nearest`, then $|\varepsilon| \leq 2^{\lfloor\log_2 |\arctan
1098    ///   x|\rfloor-p}$, where $p$ is the precision of the input.
1099    ///
1100    /// If the output has a precision, it is the precision of the input.
1101    ///
1102    /// Special cases:
1103    /// - $f(\text{NaN},m)=\text{NaN}$
1104    /// - $f(\pm\infty,m)=\pm\pi/2$, rounded
1105    /// - $f(\pm0.0,m)=1.0$
1106    ///
1107    /// Overflow and underflow:
1108    /// - Since $|\arctan x| < \pi/2$, the result never overflows.
1109    /// - If $0<f(x,m)<2^{-2^{30}}$, and $m$ is `Floor` or `Down`, $0.0$ is returned instead.
1110    /// - If $0<f(x,m)<2^{-2^{30}}$, and $m$ is `Ceiling` or `Up`, $2^{-2^{30}}$ is returned
1111    ///   instead.
1112    /// - If $0<f(x,m)\leq2^{-2^{30}-1}$, and $m$ is `Nearest`, $0.0$ is returned instead.
1113    /// - If $2^{-2^{30}-1}<f(x,m)<2^{-2^{30}}$, and $m$ is `Nearest`, $2^{-2^{30}}$ is returned
1114    ///   instead.
1115    /// - If $-2^{-2^{30}}<f(x,m)<0$, and $m$ is `Ceiling` or `Down`, $-0.0$ is returned instead.
1116    /// - If $-2^{-2^{30}}<f(x,m)<0$, and $m$ is `Floor` or `Up`, $-2^{-2^{30}}$ is returned
1117    ///   instead.
1118    /// - If $-2^{-2^{30}-1}\leq f(x,m)<0$, and $m$ is `Nearest`, $-0.0$ is returned instead.
1119    /// - If $-2^{-2^{30}}<f(x,m)<-2^{-2^{30}-1}$, and $m$ is `Nearest`, $-2^{-2^{30}}$ is returned
1120    ///   instead.
1121    ///
1122    /// Underflow requires an input of magnitude $2^{-2^{30}}$, the smallest positive [`Float`],
1123    /// rounded toward zero: since $|\arctan x| < |x|$ for nonzero $x$, no other input can reach it.
1124    ///
1125    /// If you want to specify an output precision, consider using [`Float::atan_prec_round`]
1126    /// instead. If you know you'll be using the `Nearest` rounding mode, consider using
1127    /// [`Float::atan`] instead.
1128    ///
1129    /// # Worst-case complexity
1130    /// $T(n) = O(n (\log n)^3 \log\log n)$
1131    ///
1132    /// $M(n) = O(n \log n)$
1133    ///
1134    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`: an input
1135    /// above 1 in magnitude is first inverted, and the argument is then halved a logarithmic number
1136    /// of times and split into chunks whose arctangents are summed by binary splitting, all at a
1137    /// working precision of about $n$. The magnitude of the input does not drive the cost.
1138    ///
1139    /// # Panics
1140    /// Panics if `rm` is `Exact` and `self` is nonzero and not NaN, since the arctangent of a
1141    /// finite nonzero [`Float`] is never exactly representable and neither is $\pm\pi/2$.
1142    ///
1143    /// # Examples
1144    /// ```
1145    /// use malachite_base::rounding_modes::RoundingMode::*;
1146    /// use malachite_float::Float;
1147    /// use std::cmp::Ordering::*;
1148    ///
1149    /// let (c, o) = Float::from_unsigned_prec(1u32, 100).0.atan_round(Floor);
1150    /// assert_eq!(c.to_string(), "0.78539816339744830961566084581983");
1151    /// assert_eq!(o, Less);
1152    ///
1153    /// let (c, o) = Float::from_unsigned_prec(1u32, 100).0.atan_round(Ceiling);
1154    /// assert_eq!(c.to_string(), "0.78539816339744830961566084582062");
1155    /// assert_eq!(o, Greater);
1156    ///
1157    /// let (c, o) = Float::from_unsigned_prec(1u32, 100).0.atan_round(Nearest);
1158    /// assert_eq!(c.to_string(), "0.78539816339744830961566084581983");
1159    /// assert_eq!(o, Less);
1160    /// ```
1161    #[inline]
1162    pub fn atan_round(self, rm: RoundingMode) -> (Self, Ordering) {
1163        let prec = self.significant_bits();
1164        self.atan_prec_round(prec, rm)
1165    }
1166
1167    /// Computes $\arctan x$, the arctangent of a [`Float`], rounding the result with the specified
1168    /// rounding mode. The [`Float`] is taken by reference. An [`Ordering`] is also returned,
1169    /// indicating whether the rounded arctangent is less than, equal to, or greater than the exact
1170    /// arctangent. Although `NaN`s are not comparable to any [`Float`], whenever this function
1171    /// returns a `NaN` it also returns `Equal`.
1172    ///
1173    /// The precision of the output is the precision of the input. See [`RoundingMode`] for a
1174    /// description of the possible rounding modes.
1175    ///
1176    /// $$
1177    /// f(x,m) = \arctan x+\varepsilon.
1178    /// $$
1179    /// - If $x$ is NaN, $\varepsilon$ may be ignored or assumed to be 0.
1180    /// - If $x$ is not NaN and $m$ is not `Nearest`, then $|\varepsilon| < 2^{\lfloor\log_2
1181    ///   |\arctan x|\rfloor-p+1}$, where $p$ is the precision of the input.
1182    /// - If $x$ is not NaN and $m$ is `Nearest`, then $|\varepsilon| \leq 2^{\lfloor\log_2 |\arctan
1183    ///   x|\rfloor-p}$, where $p$ is the precision of the input.
1184    ///
1185    /// If the output has a precision, it is the precision of the input.
1186    ///
1187    /// Special cases:
1188    /// - $f(\text{NaN},m)=\text{NaN}$
1189    /// - $f(\pm\infty,m)=\pm\pi/2$, rounded
1190    /// - $f(\pm0.0,m)=1.0$
1191    ///
1192    /// Overflow and underflow:
1193    /// - Since $|\arctan x| < \pi/2$, the result never overflows.
1194    /// - If $0<f(x,m)<2^{-2^{30}}$, and $m$ is `Floor` or `Down`, $0.0$ is returned instead.
1195    /// - If $0<f(x,m)<2^{-2^{30}}$, and $m$ is `Ceiling` or `Up`, $2^{-2^{30}}$ is returned
1196    ///   instead.
1197    /// - If $0<f(x,m)\leq2^{-2^{30}-1}$, and $m$ is `Nearest`, $0.0$ is returned instead.
1198    /// - If $2^{-2^{30}-1}<f(x,m)<2^{-2^{30}}$, and $m$ is `Nearest`, $2^{-2^{30}}$ is returned
1199    ///   instead.
1200    /// - If $-2^{-2^{30}}<f(x,m)<0$, and $m$ is `Ceiling` or `Down`, $-0.0$ is returned instead.
1201    /// - If $-2^{-2^{30}}<f(x,m)<0$, and $m$ is `Floor` or `Up`, $-2^{-2^{30}}$ is returned
1202    ///   instead.
1203    /// - If $-2^{-2^{30}-1}\leq f(x,m)<0$, and $m$ is `Nearest`, $-0.0$ is returned instead.
1204    /// - If $-2^{-2^{30}}<f(x,m)<-2^{-2^{30}-1}$, and $m$ is `Nearest`, $-2^{-2^{30}}$ is returned
1205    ///   instead.
1206    ///
1207    /// Underflow requires an input of magnitude $2^{-2^{30}}$, the smallest positive [`Float`],
1208    /// rounded toward zero: since $|\arctan x| < |x|$ for nonzero $x$, no other input can reach it.
1209    ///
1210    /// If you want to specify an output precision, consider using [`Float::atan_prec_round_ref`]
1211    /// instead. If you know you'll be using the `Nearest` rounding mode, consider using
1212    /// `(&Float).atan()` instead.
1213    ///
1214    /// # Worst-case complexity
1215    /// $T(n) = O(n (\log n)^3 \log\log n)$
1216    ///
1217    /// $M(n) = O(n \log n)$
1218    ///
1219    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`: an input
1220    /// above 1 in magnitude is first inverted, and the argument is then halved a logarithmic number
1221    /// of times and split into chunks whose arctangents are summed by binary splitting, all at a
1222    /// working precision of about $n$. The magnitude of the input does not drive the cost.
1223    ///
1224    /// # Panics
1225    /// Panics if `rm` is `Exact` and `self` is nonzero and not NaN, since the arctangent of a
1226    /// finite nonzero [`Float`] is never exactly representable and neither is $\pm\pi/2$.
1227    ///
1228    /// # Examples
1229    /// ```
1230    /// use malachite_base::rounding_modes::RoundingMode::*;
1231    /// use malachite_float::Float;
1232    /// use std::cmp::Ordering::*;
1233    ///
1234    /// let (c, o) = (&Float::from_unsigned_prec(1u32, 100).0).atan_round_ref(Floor);
1235    /// assert_eq!(c.to_string(), "0.78539816339744830961566084581983");
1236    /// assert_eq!(o, Less);
1237    ///
1238    /// let (c, o) = (&Float::from_unsigned_prec(1u32, 100).0).atan_round_ref(Ceiling);
1239    /// assert_eq!(c.to_string(), "0.78539816339744830961566084582062");
1240    /// assert_eq!(o, Greater);
1241    ///
1242    /// let (c, o) = (&Float::from_unsigned_prec(1u32, 100).0).atan_round_ref(Nearest);
1243    /// assert_eq!(c.to_string(), "0.78539816339744830961566084581983");
1244    /// assert_eq!(o, Less);
1245    /// ```
1246    #[inline]
1247    pub fn atan_round_ref(&self, rm: RoundingMode) -> (Self, Ordering) {
1248        self.atan_prec_round_ref(self.significant_bits(), rm)
1249    }
1250
1251    /// Computes $\arctan x$, the arctangent of a [`Float`], rounding the result to the specified
1252    /// precision and with the specified rounding mode. The [`Float`] is replaced by the result, and
1253    /// an [`Ordering`] is returned, indicating whether the rounded arctangent is less than, equal
1254    /// to, or greater than the exact arctangent. Although `NaN`s are not comparable to any
1255    /// [`Float`], whenever this function sets a `NaN` it also returns `Equal`.
1256    ///
1257    /// See [`RoundingMode`] for a description of the possible rounding modes.
1258    ///
1259    /// $$
1260    /// x \gets \arctan x+\varepsilon.
1261    /// $$
1262    /// - If $x$ is NaN, $\varepsilon$ may be ignored or assumed to be 0.
1263    /// - If $x$ is not NaN and $m$ is not `Nearest`, then $|\varepsilon| < 2^{\lfloor\log_2
1264    ///   |\arctan x|\rfloor-p+1}$.
1265    /// - If $x$ is not NaN and $m$ is `Nearest`, then $|\varepsilon| \leq 2^{\lfloor\log_2 |\arctan
1266    ///   x|\rfloor-p}$.
1267    ///
1268    /// If the output has a precision, it is `prec`.
1269    ///
1270    /// See the [`Float::atan_prec_round`] documentation for information on special cases, overflow,
1271    /// and underflow.
1272    ///
1273    /// If you know you'll be using `Nearest`, consider using [`Float::atan_prec_assign`] instead.
1274    /// If you know that your target precision is the precision of the input, consider using
1275    /// [`Float::atan_round_assign`] instead. If both of these things are true, consider using
1276    /// [`Float::atan_assign`] instead.
1277    ///
1278    /// # Worst-case complexity
1279    /// $T(n, m) = O(n (\log n)^3 \log\log n + (n+m) (\log (n+m))^2 \log\log (n+m))$
1280    ///
1281    /// $M(n, m) = O((n+m) \log (n+m))$
1282    ///
1283    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
1284    /// `self.significant_bits()`: an input above 1 in magnitude is first inverted, and the argument
1285    /// is then halved a logarithmic number of times and split into chunks whose arctangents are
1286    /// summed by binary splitting, all at a working precision of about $n$; the summation is the
1287    /// first term, and the inversion of the $m$-bit input the second. The magnitude of the input
1288    /// does not drive the cost.
1289    ///
1290    /// # Panics
1291    /// Panics if `rm` is `Exact` and `self` is nonzero and not NaN, since the arctangent of a
1292    /// finite nonzero [`Float`] is never exactly representable and neither is $\pm\pi/2$, or if
1293    /// `prec` is zero.
1294    ///
1295    /// # Examples
1296    /// ```
1297    /// use malachite_base::rounding_modes::RoundingMode::*;
1298    /// use malachite_float::Float;
1299    /// use std::cmp::Ordering::*;
1300    ///
1301    /// let mut x = Float::from_unsigned_prec(1u32, 100).0;
1302    /// assert_eq!(x.atan_prec_round_assign(5, Floor), Less);
1303    /// assert_eq!(x.to_string(), "0.781");
1304    ///
1305    /// let mut x = Float::from_unsigned_prec(1u32, 100).0;
1306    /// assert_eq!(x.atan_prec_round_assign(5, Ceiling), Greater);
1307    /// assert_eq!(x.to_string(), "0.812");
1308    ///
1309    /// let mut x = Float::from_unsigned_prec(1u32, 100).0;
1310    /// assert_eq!(x.atan_prec_round_assign(5, Nearest), Less);
1311    /// assert_eq!(x.to_string(), "0.781");
1312    ///
1313    /// let mut x = Float::from_unsigned_prec(1u32, 100).0;
1314    /// assert_eq!(x.atan_prec_round_assign(20, Floor), Less);
1315    /// assert_eq!(x.to_string(), "0.78539753");
1316    ///
1317    /// let mut x = Float::from_unsigned_prec(1u32, 100).0;
1318    /// assert_eq!(x.atan_prec_round_assign(20, Ceiling), Greater);
1319    /// assert_eq!(x.to_string(), "0.78539848");
1320    ///
1321    /// let mut x = Float::from_unsigned_prec(1u32, 100).0;
1322    /// assert_eq!(x.atan_prec_round_assign(20, Nearest), Greater);
1323    /// assert_eq!(x.to_string(), "0.78539848");
1324    /// ```
1325    #[inline]
1326    pub fn atan_prec_round_assign(&mut self, prec: u64, rm: RoundingMode) -> Ordering {
1327        let o;
1328        (*self, o) = self.atan_prec_round_ref(prec, rm);
1329        o
1330    }
1331
1332    /// Computes $\arctan x$, the arctangent of a [`Float`], rounding the result to the nearest
1333    /// value of the specified precision. The [`Float`] is replaced by the result, and an
1334    /// [`Ordering`] is returned, indicating whether the rounded arctangent is less than, equal to,
1335    /// or greater than the exact arctangent. Although `NaN`s are not comparable to any [`Float`],
1336    /// whenever this function sets a `NaN` it also returns `Equal`.
1337    ///
1338    /// If the arctangent is equidistant from two [`Float`]s with the specified precision, the
1339    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
1340    /// description of the `Nearest` rounding mode.
1341    ///
1342    /// $$
1343    /// x \gets \arctan x+\varepsilon.
1344    /// $$
1345    /// - If $x$ is NaN, $\varepsilon$ may be ignored or assumed to be 0.
1346    /// - If $x$ is not NaN, then $|\varepsilon| < 2^{\lfloor\log_2 |\arctan x|\rfloor-p}$.
1347    ///
1348    /// If the output has a precision, it is `prec`.
1349    ///
1350    /// See the [`Float::atan_prec`] documentation for information on special cases, overflow, and
1351    /// underflow.
1352    ///
1353    /// If you want to use a rounding mode other than `Nearest`, consider using
1354    /// [`Float::atan_prec_round_assign`] instead. If you know that your target precision is the
1355    /// precision of the input, consider using [`Float::atan_assign`] instead.
1356    ///
1357    /// # Worst-case complexity
1358    /// $T(n, m) = O(n (\log n)^3 \log\log n + (n+m) (\log (n+m))^2 \log\log (n+m))$
1359    ///
1360    /// $M(n, m) = O((n+m) \log (n+m))$
1361    ///
1362    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
1363    /// `self.significant_bits()`: an input above 1 in magnitude is first inverted, and the argument
1364    /// is then halved a logarithmic number of times and split into chunks whose arctangents are
1365    /// summed by binary splitting, all at a working precision of about $n$; the summation is the
1366    /// first term, and the inversion of the $m$-bit input the second. The magnitude of the input
1367    /// does not drive the cost.
1368    ///
1369    /// # Panics
1370    /// Panics if `prec` is zero.
1371    ///
1372    /// # Examples
1373    /// ```
1374    /// use malachite_float::Float;
1375    /// use std::cmp::Ordering::*;
1376    ///
1377    /// let mut x = Float::from_unsigned_prec(1u32, 100).0;
1378    /// assert_eq!(x.atan_prec_assign(5), Less);
1379    /// assert_eq!(x.to_string(), "0.781");
1380    ///
1381    /// let mut x = Float::from_unsigned_prec(1u32, 100).0;
1382    /// assert_eq!(x.atan_prec_assign(20), Greater);
1383    /// assert_eq!(x.to_string(), "0.78539848");
1384    /// ```
1385    #[inline]
1386    pub fn atan_prec_assign(&mut self, prec: u64) -> Ordering {
1387        self.atan_prec_round_assign(prec, Nearest)
1388    }
1389
1390    /// Computes $\arctan x$, the arctangent of a [`Float`], rounding the result with the specified
1391    /// rounding mode. The [`Float`] is replaced by the result, and an [`Ordering`] is returned,
1392    /// indicating whether the rounded arctangent is less than, equal to, or greater than the exact
1393    /// arctangent. Although `NaN`s are not comparable to any [`Float`], whenever this function sets
1394    /// a `NaN` it also returns `Equal`.
1395    ///
1396    /// The precision of the output is the precision of the input. See [`RoundingMode`] for a
1397    /// description of the possible rounding modes.
1398    ///
1399    /// $$
1400    /// x \gets \arctan x+\varepsilon.
1401    /// $$
1402    /// - If $x$ is NaN, $\varepsilon$ may be ignored or assumed to be 0.
1403    /// - If $x$ is not NaN and $m$ is not `Nearest`, then $|\varepsilon| < 2^{\lfloor\log_2
1404    ///   |\arctan x|\rfloor-p+1}$, where $p$ is the precision of the input.
1405    /// - If $x$ is not NaN and $m$ is `Nearest`, then $|\varepsilon| \leq 2^{\lfloor\log_2 |\arctan
1406    ///   x|\rfloor-p}$, where $p$ is the precision of the input.
1407    ///
1408    /// If the output has a precision, it is the precision of the input.
1409    ///
1410    /// See the [`Float::atan_round`] documentation for information on special cases, overflow, and
1411    /// underflow.
1412    ///
1413    /// If you want to specify an output precision, consider using [`Float::atan_prec_round_assign`]
1414    /// instead. If you know you'll be using the `Nearest` rounding mode, consider using
1415    /// [`Float::atan_assign`] instead.
1416    ///
1417    /// # Worst-case complexity
1418    /// $T(n) = O(n (\log n)^3 \log\log n)$
1419    ///
1420    /// $M(n) = O(n \log n)$
1421    ///
1422    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`: an input
1423    /// above 1 in magnitude is first inverted, and the argument is then halved a logarithmic number
1424    /// of times and split into chunks whose arctangents are summed by binary splitting, all at a
1425    /// working precision of about $n$. The magnitude of the input does not drive the cost.
1426    ///
1427    /// # Panics
1428    /// Panics if `rm` is `Exact` and `self` is nonzero and not NaN, since the arctangent of a
1429    /// finite nonzero [`Float`] is never exactly representable and neither is $\pm\pi/2$.
1430    ///
1431    /// # Examples
1432    /// ```
1433    /// use malachite_base::rounding_modes::RoundingMode::*;
1434    /// use malachite_float::Float;
1435    /// use std::cmp::Ordering::*;
1436    ///
1437    /// let mut x = Float::from_unsigned_prec(1u32, 100).0;
1438    /// assert_eq!(x.atan_round_assign(Floor), Less);
1439    /// assert_eq!(x.to_string(), "0.78539816339744830961566084581983");
1440    ///
1441    /// let mut x = Float::from_unsigned_prec(1u32, 100).0;
1442    /// assert_eq!(x.atan_round_assign(Ceiling), Greater);
1443    /// assert_eq!(x.to_string(), "0.78539816339744830961566084582062");
1444    ///
1445    /// let mut x = Float::from_unsigned_prec(1u32, 100).0;
1446    /// assert_eq!(x.atan_round_assign(Nearest), Less);
1447    /// assert_eq!(x.to_string(), "0.78539816339744830961566084581983");
1448    /// ```
1449    #[inline]
1450    pub fn atan_round_assign(&mut self, rm: RoundingMode) -> Ordering {
1451        let prec = self.significant_bits();
1452        self.atan_prec_round_assign(prec, rm)
1453    }
1454}
1455
1456impl Float {
1457    /// Computes $\arctan(x)u/(2\pi)$, the arctangent of a [`Float`] measured in $u$ths of a turn,
1458    /// rounding the result to the specified precision and with the specified rounding mode. The
1459    /// [`Float`] is taken by value. An [`Ordering`] is also returned, indicating whether the
1460    /// rounded arctangent is less than, equal to, or greater than the exact arctangent. Although
1461    /// `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN` it also
1462    /// returns `Equal`.
1463    ///
1464    /// See [`RoundingMode`] for a description of the possible rounding modes.
1465    ///
1466    /// $$
1467    /// f(x,u,p,m) = \arctan(x)u/(2\pi)+\varepsilon.
1468    /// $$
1469    /// - If $x$ is NaN or zero, $u = 0$, or $|x|$ is 1 or infinite, $\varepsilon$ may be ignored or
1470    ///   assumed to be 0.
1471    /// - Otherwise, if $m$ is not `Nearest`, then $|\varepsilon| < 2^{\lfloor\log_2
1472    ///   |\arctan(x)u/(2\pi)|\rfloor-p+1}$.
1473    /// - Otherwise, if $m$ is `Nearest`, then $|\varepsilon| \leq 2^{\lfloor\log_2
1474    ///   |\arctan(x)u/(2\pi)|\rfloor-p}$.
1475    ///
1476    /// If the output has a precision, it is `prec`.
1477    ///
1478    /// Special cases:
1479    /// - $f(\text{NaN},u,p,m)=\text{NaN}$
1480    /// - $f(\pm\infty,u,p,m)=\pm u/4$, a quarter turn
1481    /// - $f(\pm0.0,u,p,m)=\pm0.0$
1482    /// - $f(x,0,p,m)=\pm0.0$, with the sign of $x$, so that the function stays odd
1483    /// - $f(\pm1,u,p,m)=\pm u/8$, an eighth of a turn
1484    ///
1485    /// The last three are the only exact cases, and the quarter and eighth turns are exact only
1486    /// when $p$ is large enough to hold them.
1487    ///
1488    /// Underflow:
1489    /// - If $0<f(x,u,p,m)<2^{-2^{30}}$, and $m$ is `Floor` or `Down`, $0.0$ is returned instead.
1490    /// - If $0<f(x,u,p,m)<2^{-2^{30}}$, and $m$ is `Ceiling` or `Up`, $2^{-2^{30}}$ is returned
1491    ///   instead.
1492    /// - If $0<f(x,u,p,m)\leq2^{-2^{30}-1}$, and $m$ is `Nearest`, $0.0$ is returned instead.
1493    /// - If $2^{-2^{30}-1}<f(x,u,p,m)<2^{-2^{30}}$, and $m$ is `Nearest`, $2^{-2^{30}}$ is returned
1494    ///   instead.
1495    /// - The negative cases mirror these, since the function is odd.
1496    ///
1497    /// Overflow is not possible, since $|f(x,u,p,m)| < u/4 < 2^{62}$. Underflow requires a tiny $x$
1498    /// together with a small $u$, since the result is about $xu/(2\pi)$ there.
1499    ///
1500    /// If you know you'll be using `Nearest`, consider using [`Float::atan_with_period_prec`]
1501    /// instead. If you know that your target precision is the precision of the input, consider
1502    /// using [`Float::atan_with_period_round`] instead.
1503    ///
1504    /// # Worst-case complexity
1505    /// $T(n, m) = O(n (\log n)^3 \log\log n + (n+m) (\log (n+m))^2 \log\log (n+m))$
1506    ///
1507    /// $M(n, m) = O((n+m) \log (n+m))$
1508    ///
1509    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
1510    /// `self.significant_bits()`: the arctangent is taken at a working precision of about $n$ bits,
1511    /// which costs the first term, and is then scaled by $u/(2\pi)$, which needs $\pi$ to that many
1512    /// bits; the second term covers the $m$-bit input. The magnitude of the input does not drive
1513    /// the cost.
1514    ///
1515    /// # Panics
1516    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
1517    /// with the given precision (which is the case unless $x$ is zero or NaN, $u$ is zero, or $|x|$
1518    /// is 1 or infinite and $p$ is large enough to hold a quarter or an eighth of a turn).
1519    ///
1520    /// # Examples
1521    /// ```
1522    /// use malachite_base::num::basic::traits::{One, Two};
1523    /// use malachite_base::rounding_modes::RoundingMode::*;
1524    /// use malachite_float::Float;
1525    /// use std::cmp::Ordering::*;
1526    ///
1527    /// let (t, o) = Float::ONE.atan_with_period_prec_round(360, 10, Exact);
1528    /// assert_eq!(t.to_string(), "45.000");
1529    /// assert_eq!(o, Equal);
1530    ///
1531    /// let (t, o) = Float::TWO.atan_with_period_prec_round(360, 10, Floor);
1532    /// assert_eq!(t.to_string(), "63.375");
1533    /// assert_eq!(o, Less);
1534    ///
1535    /// let (t, o) = Float::TWO.atan_with_period_prec_round(360, 10, Ceiling);
1536    /// assert_eq!(t.to_string(), "63.438");
1537    /// assert_eq!(o, Greater);
1538    /// ```
1539    #[inline]
1540    pub fn atan_with_period_prec_round(
1541        self,
1542        u: u64,
1543        prec: u64,
1544        rm: RoundingMode,
1545    ) -> (Self, Ordering) {
1546        self.atan_with_period_prec_round_ref(u, prec, rm)
1547    }
1548
1549    /// Computes $\arctan(x)u/(2\pi)$, the arctangent of a [`Float`] measured in $u$ths of a turn,
1550    /// rounding the result to the specified precision and with the specified rounding mode. The
1551    /// [`Float`] is taken by reference. An [`Ordering`] is also returned, indicating whether the
1552    /// rounded arctangent is less than, equal to, or greater than the exact arctangent. Although
1553    /// `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN` it also
1554    /// returns `Equal`.
1555    ///
1556    /// See [`Float::atan_with_period_prec_round`] for the error bounds, the special and closed-form
1557    /// cases, overflow, and the complexity; this function behaves the same way.
1558    ///
1559    /// # Panics
1560    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
1561    /// with the given precision.
1562    ///
1563    /// # Examples
1564    /// ```
1565    /// use malachite_base::num::basic::traits::{One, Two};
1566    /// use malachite_base::rounding_modes::RoundingMode::*;
1567    /// use malachite_float::Float;
1568    /// use std::cmp::Ordering::*;
1569    ///
1570    /// let (t, o) = (&Float::ONE).atan_with_period_prec_round_ref(360, 10, Exact);
1571    /// assert_eq!(t.to_string(), "45.000");
1572    /// assert_eq!(o, Equal);
1573    ///
1574    /// let (t, o) = (&Float::TWO).atan_with_period_prec_round_ref(360, 10, Floor);
1575    /// assert_eq!(t.to_string(), "63.375");
1576    /// assert_eq!(o, Less);
1577    /// ```
1578    pub fn atan_with_period_prec_round_ref(
1579        &self,
1580        u: u64,
1581        prec: u64,
1582        rm: RoundingMode,
1583    ) -> (Self, Ordering) {
1584        assert_ne!(prec, 0);
1585        match &self.0 {
1586            NaN => (Self::NAN, Equal),
1587            // atanu(+infinity, u) = u/4, atanu(-infinity, u) = -u/4, a quarter turn
1588            Infinity { sign } => {
1589                if u == 0 {
1590                    (
1591                        if *sign {
1592                            Self::ZERO
1593                        } else {
1594                            Self::NEGATIVE_ZERO
1595                        },
1596                        Equal,
1597                    )
1598                } else {
1599                    scaled_unsigned(u, 2, *sign, prec, rm)
1600                }
1601            }
1602            // atanu(±0.0, u) = ±0.0, even for u = 0
1603            Zero { .. } => (self.clone(), Equal),
1604            Finite { .. } => {
1605                if u == 0 {
1606                    // atanu(x, 0) = 0 with the sign of x, which agrees with the x = 0 case and
1607                    // keeps the function odd
1608                    (
1609                        if *self < 0u32 {
1610                            Self::NEGATIVE_ZERO
1611                        } else {
1612                            Self::ZERO
1613                        },
1614                        Equal,
1615                    )
1616                } else {
1617                    atan_with_period_prec_round_normal_ref(self, u, prec, rm)
1618                }
1619            }
1620        }
1621    }
1622
1623    /// Computes $\arctan(x)u/(2\pi)$, the arctangent of a [`Float`] measured in $u$ths of a turn,
1624    /// rounding the result to the nearest value of the specified precision. The [`Float`] is taken
1625    /// by value. An [`Ordering`] is also returned, indicating whether the rounded arctangent is
1626    /// less than, equal to, or greater than the exact arctangent. Although `NaN`s are not
1627    /// comparable to any [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
1628    ///
1629    /// If the arctangent is equidistant from two [`Float`]s with the specified precision, the
1630    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
1631    /// description of the `Nearest` rounding mode.
1632    ///
1633    /// See [`Float::atan_with_period_prec_round`] for the error bounds, the special and closed-form
1634    /// cases, overflow, and the complexity; this function behaves the same way with `Nearest`.
1635    ///
1636    /// If you want to use a rounding mode other than `Nearest`, consider using
1637    /// [`Float::atan_with_period_prec_round`] instead.
1638    ///
1639    /// # Panics
1640    /// Panics if `prec` is zero.
1641    ///
1642    /// # Examples
1643    /// ```
1644    /// use malachite_base::num::basic::traits::{One, Two};
1645    /// use malachite_float::Float;
1646    /// use std::cmp::Ordering::*;
1647    ///
1648    /// let (t, o) = Float::ONE.atan_with_period_prec(360, 10);
1649    /// assert_eq!(t.to_string(), "45.000");
1650    /// assert_eq!(o, Equal);
1651    ///
1652    /// let (t, o) = Float::TWO.atan_with_period_prec(360, 10);
1653    /// assert_eq!(t.to_string(), "63.438");
1654    /// assert_eq!(o, Greater);
1655    /// ```
1656    #[inline]
1657    pub fn atan_with_period_prec(self, u: u64, prec: u64) -> (Self, Ordering) {
1658        self.atan_with_period_prec_round(u, prec, Nearest)
1659    }
1660
1661    /// Computes $\arctan(x)u/(2\pi)$, the arctangent of a [`Float`] measured in $u$ths of a turn,
1662    /// rounding the result to the nearest value of the specified precision. The [`Float`] is taken
1663    /// by reference. An [`Ordering`] is also returned, indicating whether the rounded arctangent is
1664    /// less than, equal to, or greater than the exact arctangent. Although `NaN`s are not
1665    /// comparable to any [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
1666    ///
1667    /// See [`Float::atan_with_period_prec`] and [`Float::atan_with_period_prec_round`]; this
1668    /// function behaves the same way.
1669    ///
1670    /// # Panics
1671    /// Panics if `prec` is zero.
1672    ///
1673    /// # Examples
1674    /// ```
1675    /// use malachite_base::num::basic::traits::Two;
1676    /// use malachite_float::Float;
1677    /// use std::cmp::Ordering::*;
1678    ///
1679    /// let (t, o) = (&Float::TWO).atan_with_period_prec_ref(360, 10);
1680    /// assert_eq!(t.to_string(), "63.438");
1681    /// assert_eq!(o, Greater);
1682    /// ```
1683    #[inline]
1684    pub fn atan_with_period_prec_ref(&self, u: u64, prec: u64) -> (Self, Ordering) {
1685        self.atan_with_period_prec_round_ref(u, prec, Nearest)
1686    }
1687
1688    /// Computes $\arctan(x)u/(2\pi)$, the arctangent of a [`Float`] measured in $u$ths of a turn,
1689    /// rounding the result to the precision of the input and with the specified rounding mode. The
1690    /// [`Float`] is taken by value. An [`Ordering`] is also returned, indicating whether the
1691    /// rounded arctangent is less than, equal to, or greater than the exact arctangent. Although
1692    /// `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN` it also
1693    /// returns `Equal`.
1694    ///
1695    /// See [`Float::atan_with_period_prec_round`] for the error bounds, the special and closed-form
1696    /// cases, overflow, and the complexity; this function behaves the same way with `prec` equal to
1697    /// the precision of the input.
1698    ///
1699    /// If you want to specify an output precision, consider using
1700    /// [`Float::atan_with_period_prec_round`] instead.
1701    ///
1702    /// # Panics
1703    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the precision of
1704    /// the input.
1705    ///
1706    /// # Examples
1707    /// ```
1708    /// use malachite_base::rounding_modes::RoundingMode::*;
1709    /// use malachite_float::Float;
1710    /// use std::cmp::Ordering::*;
1711    ///
1712    /// // the output takes the input's precision, here 10 bits
1713    /// let (t, o) = Float::from_unsigned_prec(2u32, 10)
1714    ///     .0
1715    ///     .atan_with_period_round(360, Floor);
1716    /// assert_eq!(t.to_string(), "63.375");
1717    /// assert_eq!(o, Less);
1718    /// ```
1719    #[inline]
1720    pub fn atan_with_period_round(self, u: u64, rm: RoundingMode) -> (Self, Ordering) {
1721        let prec = self.significant_bits();
1722        self.atan_with_period_prec_round(u, prec, rm)
1723    }
1724
1725    /// Computes $\arctan(x)u/(2\pi)$, the arctangent of a [`Float`] measured in $u$ths of a turn,
1726    /// rounding the result to the precision of the input and with the specified rounding mode. The
1727    /// [`Float`] is taken by reference. An [`Ordering`] is also returned, indicating whether the
1728    /// rounded arctangent is less than, equal to, or greater than the exact arctangent. Although
1729    /// `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN` it also
1730    /// returns `Equal`.
1731    ///
1732    /// See [`Float::atan_with_period_round`] and [`Float::atan_with_period_prec_round`]; this
1733    /// function behaves the same way.
1734    ///
1735    /// # Panics
1736    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the precision of
1737    /// the input.
1738    ///
1739    /// # Examples
1740    /// ```
1741    /// use malachite_base::rounding_modes::RoundingMode::*;
1742    /// use malachite_float::Float;
1743    /// use std::cmp::Ordering::*;
1744    ///
1745    /// // the output takes the input's precision, here 10 bits
1746    /// let x = Float::from_unsigned_prec(2u32, 10).0;
1747    /// let (t, o) = (&x).atan_with_period_round_ref(360, Floor);
1748    /// assert_eq!(t.to_string(), "63.375");
1749    /// assert_eq!(o, Less);
1750    /// ```
1751    #[inline]
1752    pub fn atan_with_period_round_ref(&self, u: u64, rm: RoundingMode) -> (Self, Ordering) {
1753        self.atan_with_period_prec_round_ref(u, self.significant_bits(), rm)
1754    }
1755
1756    /// Computes $\arctan(x)u/(2\pi)$, the arctangent of a [`Float`] measured in $u$ths of a turn
1757    /// (so that `u = 360` is degrees), rounding the result to the precision of the input and to the
1758    /// nearest [`Float`]. The [`Float`] is taken by value.
1759    ///
1760    /// If the arctangent is equidistant from two [`Float`]s with the precision of the input, the
1761    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
1762    /// description of the `Nearest` rounding mode.
1763    ///
1764    /// See [`Float::atan_with_period_prec_round`] for the error bounds, the special and closed-form
1765    /// cases, overflow, and the complexity; this function behaves the same way with `prec` equal to
1766    /// the precision of the input and `rm` equal to `Nearest`.
1767    ///
1768    /// If you want to use a rounding mode other than `Nearest`, consider using
1769    /// [`Float::atan_with_period_round`] instead. If you want to specify an output precision,
1770    /// consider using [`Float::atan_with_period_prec`]. If you want both of these things, consider
1771    /// using [`Float::atan_with_period_prec_round`].
1772    ///
1773    /// # Examples
1774    /// ```
1775    /// use malachite_float::Float;
1776    ///
1777    /// let t = Float::from_unsigned_prec(2u32, 10).0.atan_with_period(360);
1778    /// assert_eq!(t.to_string(), "63.438");
1779    /// ```
1780    #[inline]
1781    pub fn atan_with_period(self, u: u64) -> Self {
1782        let prec = self.significant_bits();
1783        self.atan_with_period_prec(u, prec).0
1784    }
1785
1786    /// Computes $\arctan(x)u/(2\pi)$, the arctangent of a [`Float`] measured in $u$ths of a turn
1787    /// (so that `u = 360` is degrees), rounding the result to the precision of the input and to the
1788    /// nearest [`Float`]. The [`Float`] is taken by reference.
1789    ///
1790    /// If the arctangent is equidistant from two [`Float`]s with the precision of the input, the
1791    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
1792    /// description of the `Nearest` rounding mode.
1793    ///
1794    /// See [`Float::atan_with_period_prec_round`] for the error bounds, the special and closed-form
1795    /// cases, overflow, and the complexity; this function behaves the same way with `prec` equal to
1796    /// the precision of the input and `rm` equal to `Nearest`.
1797    ///
1798    /// If you want to use a rounding mode other than `Nearest`, consider using
1799    /// [`Float::atan_with_period_round_ref`] instead. If you want to specify an output precision,
1800    /// consider using [`Float::atan_with_period_prec_ref`]. If you want both of these things,
1801    /// consider using [`Float::atan_with_period_prec_round_ref`].
1802    ///
1803    /// # Examples
1804    /// ```
1805    /// use malachite_float::Float;
1806    ///
1807    /// let t = (&Float::from_unsigned_prec(2u32, 10).0).atan_with_period_ref(360);
1808    /// assert_eq!(t.to_string(), "63.438");
1809    /// ```
1810    #[inline]
1811    pub fn atan_with_period_ref(&self, u: u64) -> Self {
1812        self.atan_with_period_prec_ref(u, self.significant_bits()).0
1813    }
1814
1815    /// Replaces a [`Float`] measured in $u$ths of a turn with its arctangent, rounding the result
1816    /// to the specified precision and with the specified rounding mode. An [`Ordering`] is
1817    /// returned, indicating whether the rounded arctangent is less than, equal to, or greater than
1818    /// the exact arctangent. Although `NaN`s are not comparable to any [`Float`], whenever this
1819    /// function sets a `NaN` it also returns `Equal`.
1820    ///
1821    /// See [`Float::atan_with_period_prec_round`] for the error bounds, the special and closed-form
1822    /// cases, overflow, and the complexity; this function behaves the same way.
1823    ///
1824    /// # Panics
1825    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
1826    /// with the given precision.
1827    ///
1828    /// # Examples
1829    /// ```
1830    /// use malachite_base::num::basic::traits::Two;
1831    /// use malachite_base::rounding_modes::RoundingMode::*;
1832    /// use malachite_float::Float;
1833    /// use std::cmp::Ordering::*;
1834    ///
1835    /// let mut x = Float::TWO;
1836    /// let o = x.atan_with_period_prec_round_assign(360, 10, Floor);
1837    /// assert_eq!(x.to_string(), "63.375");
1838    /// assert_eq!(o, Less);
1839    /// ```
1840    #[inline]
1841    pub fn atan_with_period_prec_round_assign(
1842        &mut self,
1843        u: u64,
1844        prec: u64,
1845        rm: RoundingMode,
1846    ) -> Ordering {
1847        let (t, o) = self.atan_with_period_prec_round_ref(u, prec, rm);
1848        *self = t;
1849        o
1850    }
1851
1852    /// Replaces a [`Float`] measured in $u$ths of a turn with its arctangent, rounding the result
1853    /// to the nearest value of the specified precision. An [`Ordering`] is returned, indicating
1854    /// whether the rounded arctangent is less than, equal to, or greater than the exact arctangent.
1855    /// Although `NaN`s are not comparable to any [`Float`], whenever this function sets a `NaN` it
1856    /// also returns `Equal`.
1857    ///
1858    /// See [`Float::atan_with_period_prec`] and [`Float::atan_with_period_prec_round`]; this
1859    /// function behaves the same way.
1860    ///
1861    /// # Panics
1862    /// Panics if `prec` is zero.
1863    ///
1864    /// # Examples
1865    /// ```
1866    /// use malachite_base::num::basic::traits::Two;
1867    /// use malachite_float::Float;
1868    /// use std::cmp::Ordering::*;
1869    ///
1870    /// let mut x = Float::TWO;
1871    /// let o = x.atan_with_period_prec_assign(360, 10);
1872    /// assert_eq!(x.to_string(), "63.438");
1873    /// assert_eq!(o, Greater);
1874    /// ```
1875    #[inline]
1876    pub fn atan_with_period_prec_assign(&mut self, u: u64, prec: u64) -> Ordering {
1877        self.atan_with_period_prec_round_assign(u, prec, Nearest)
1878    }
1879
1880    /// Replaces a [`Float`] measured in $u$ths of a turn with its arctangent, rounding the result
1881    /// to the precision of the input and with the specified rounding mode. An [`Ordering`] is
1882    /// returned, indicating whether the rounded arctangent is less than, equal to, or greater than
1883    /// the exact arctangent. Although `NaN`s are not comparable to any [`Float`], whenever this
1884    /// function sets a `NaN` it also returns `Equal`.
1885    ///
1886    /// See [`Float::atan_with_period_round`] and [`Float::atan_with_period_prec_round`]; this
1887    /// function behaves the same way.
1888    ///
1889    /// # Panics
1890    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the precision of
1891    /// the input.
1892    ///
1893    /// # Examples
1894    /// ```
1895    /// use malachite_base::rounding_modes::RoundingMode::*;
1896    /// use malachite_float::Float;
1897    /// use std::cmp::Ordering::*;
1898    ///
1899    /// // the output takes the input's precision, here 10 bits
1900    /// let mut x = Float::from_unsigned_prec(2u32, 10).0;
1901    /// let o = x.atan_with_period_round_assign(360, Floor);
1902    /// assert_eq!(x.to_string(), "63.375");
1903    /// assert_eq!(o, Less);
1904    /// ```
1905    #[inline]
1906    pub fn atan_with_period_round_assign(&mut self, u: u64, rm: RoundingMode) -> Ordering {
1907        let prec = self.significant_bits();
1908        self.atan_with_period_prec_round_assign(u, prec, rm)
1909    }
1910
1911    /// Computes $\arctan(x)u/(2\pi)$, the arctangent of a [`Float`] measured in $u$ths of a turn
1912    /// (so that `u = 360` is degrees), rounding the result to the precision of the input and to the
1913    /// nearest [`Float`]. The [`Float`] is replaced by the result.
1914    ///
1915    /// If the arctangent is equidistant from two [`Float`]s with the precision of the input, the
1916    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
1917    /// description of the `Nearest` rounding mode.
1918    ///
1919    /// See [`Float::atan_with_period_prec_round`] for the error bounds, the special and closed-form
1920    /// cases, overflow, and the complexity; this function behaves the same way with `prec` equal to
1921    /// the precision of the input and `rm` equal to `Nearest`.
1922    ///
1923    /// If you want to use a rounding mode other than `Nearest`, consider using
1924    /// [`Float::atan_with_period_round_assign`] instead. If you want to specify an output
1925    /// precision, consider using [`Float::atan_with_period_prec_assign`]. If you want both of these
1926    /// things, consider using [`Float::atan_with_period_prec_round_assign`].
1927    ///
1928    /// # Examples
1929    /// ```
1930    /// use malachite_float::Float;
1931    ///
1932    /// let mut x = Float::from_unsigned_prec(2u32, 10).0;
1933    /// x.atan_with_period_assign(360);
1934    /// assert_eq!(x.to_string(), "63.438");
1935    /// ```
1936    #[inline]
1937    pub fn atan_with_period_assign(&mut self, u: u64) {
1938        let prec = self.significant_bits();
1939        self.atan_with_period_prec_assign(u, prec);
1940    }
1941}
1942
1943impl Float {
1944    /// Computes $\arctan x$, the arctangent of a [`Rational`], rounding the result to the specified
1945    /// precision and with the specified rounding mode and returning the result as a [`Float`]. The
1946    /// [`Rational`] is taken by value. An [`Ordering`] is also returned, indicating whether the
1947    /// rounded arctangent is less than, equal to, or greater than the exact arctangent.
1948    ///
1949    /// See [`RoundingMode`] for a description of the possible rounding modes.
1950    ///
1951    /// $$
1952    /// f(x,p,m) = \arctan x+\varepsilon.
1953    /// $$
1954    /// - If $m$ is not `Nearest`, then $|\varepsilon| < 2^{\lfloor\log_2 |\arctan x|\rfloor-p+1}$.
1955    /// - If $m$ is `Nearest`, then $|\varepsilon| \leq 2^{\lfloor\log_2 |\arctan x|\rfloor-p}$.
1956    ///
1957    /// These bounds do not apply when the result underflows; see below.
1958    ///
1959    /// The output has precision `prec`.
1960    ///
1961    /// Special cases:
1962    /// - $f(0,p,m)=0$.
1963    ///
1964    /// Overflow and underflow:
1965    /// - Since $|\arctan x| < \pi/2$, the result never overflows.
1966    /// - If $0<f(x,p,m)<2^{-2^{30}}$, and $m$ is `Floor` or `Down`, $0.0$ is returned instead.
1967    /// - If $0<f(x,p,m)<2^{-2^{30}}$, and $m$ is `Ceiling` or `Up`, $2^{-2^{30}}$ is returned
1968    ///   instead.
1969    /// - If $0<f(x,p,m)\leq2^{-2^{30}-1}$, and $m$ is `Nearest`, $0.0$ is returned instead.
1970    /// - If $2^{-2^{30}-1}<f(x,p,m)<2^{-2^{30}}$, and $m$ is `Nearest`, $2^{-2^{30}}$ is returned
1971    ///   instead.
1972    /// - If $-2^{-2^{30}}<f(x,p,m)<0$, and $m$ is `Ceiling` or `Down`, $-0.0$ is returned instead.
1973    /// - If $-2^{-2^{30}}<f(x,p,m)<0$, and $m$ is `Floor` or `Up`, $-2^{-2^{30}}$ is returned
1974    ///   instead.
1975    /// - If $-2^{-2^{30}-1}\leq f(x,p,m)<0$, and $m$ is `Nearest`, $-0.0$ is returned instead.
1976    /// - If $-2^{-2^{30}}<f(x,p,m)<-2^{-2^{30}-1}$, and $m$ is `Nearest`, $-2^{-2^{30}}$ is
1977    ///   returned instead.
1978    ///
1979    /// Underflow requires an input of magnitude about $2^{-2^{30}}$ or less: since $|\arctan x| <
1980    /// |x|$ for nonzero $x$, no other input can reach it.
1981    ///
1982    /// If you know you'll be using `Nearest`, consider using [`Float::atan_rational_prec`] instead.
1983    ///
1984    /// # Worst-case complexity
1985    /// $T(n, m) = O(n (\log n)^3 \log\log n + (n+m) (\log (n+m))^2 \log\log (n+m))$
1986    ///
1987    /// $M(n, m) = O((n+m) \log (n+m))$
1988    ///
1989    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
1990    /// `x.significant_bits()`: the input is rounded once to a working precision of about $n$ bits
1991    /// and its [`Float`] arctangent taken there, which costs the first term; the rounding of the
1992    /// $m$-bit input is the second. The magnitude of the input does not drive the cost.
1993    ///
1994    /// # Panics
1995    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
1996    /// with the given precision (which is the case for every nonzero input).
1997    ///
1998    /// # Examples
1999    /// ```
2000    /// use malachite_base::rounding_modes::RoundingMode::*;
2001    /// use malachite_float::Float;
2002    /// use malachite_q::Rational;
2003    /// use std::cmp::Ordering::*;
2004    ///
2005    /// let (c, o) = Float::atan_rational_prec_round(Rational::from_unsigneds(3u8, 5), 5, Floor);
2006    /// assert_eq!(c.to_string(), "0.531");
2007    /// assert_eq!(o, Less);
2008    ///
2009    /// let (c, o) = Float::atan_rational_prec_round(Rational::from_unsigneds(3u8, 5), 5, Ceiling);
2010    /// assert_eq!(c.to_string(), "0.562");
2011    /// assert_eq!(o, Greater);
2012    ///
2013    /// let (c, o) = Float::atan_rational_prec_round(Rational::from_unsigneds(3u8, 5), 20, Floor);
2014    /// assert_eq!(c.to_string(), "0.54041862");
2015    /// assert_eq!(o, Less);
2016    ///
2017    /// let (c, o) = Float::atan_rational_prec_round(Rational::from_unsigneds(3u8, 5), 20, Ceiling);
2018    /// assert_eq!(c.to_string(), "0.54041958");
2019    /// assert_eq!(o, Greater);
2020    /// ```
2021    #[inline]
2022    #[allow(clippy::needless_pass_by_value)]
2023    pub fn atan_rational_prec_round(x: Rational, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
2024        Self::atan_rational_prec_round_ref(&x, prec, rm)
2025    }
2026
2027    /// Computes $\arctan x$, the arctangent of a [`Rational`], rounding the result to the specified
2028    /// precision and with the specified rounding mode and returning the result as a [`Float`]. The
2029    /// [`Rational`] is taken by reference. An [`Ordering`] is also returned, indicating whether the
2030    /// rounded arctangent is less than, equal to, or greater than the exact arctangent.
2031    ///
2032    /// See [`RoundingMode`] for a description of the possible rounding modes.
2033    ///
2034    /// $$
2035    /// f(x,p,m) = \arctan x+\varepsilon.
2036    /// $$
2037    /// - If $m$ is not `Nearest`, then $|\varepsilon| < 2^{\lfloor\log_2 |\arctan x|\rfloor-p+1}$.
2038    /// - If $m$ is `Nearest`, then $|\varepsilon| \leq 2^{\lfloor\log_2 |\arctan x|\rfloor-p}$.
2039    ///
2040    /// These bounds do not apply when the result underflows.
2041    ///
2042    /// The output has precision `prec`.
2043    ///
2044    /// Special cases:
2045    /// - $f(0,p,m)=0$.
2046    ///
2047    /// See the [`Float::atan_rational_prec_round`] documentation for information on overflow and
2048    /// underflow.
2049    ///
2050    /// If you know you'll be using `Nearest`, consider using [`Float::atan_rational_prec_ref`]
2051    /// instead.
2052    ///
2053    /// # Worst-case complexity
2054    /// $T(n, m) = O(n (\log n)^3 \log\log n + (n+m) (\log (n+m))^2 \log\log (n+m))$
2055    ///
2056    /// $M(n, m) = O((n+m) \log (n+m))$
2057    ///
2058    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
2059    /// `x.significant_bits()`: the input is rounded once to a working precision of about $n$ bits
2060    /// and its [`Float`] arctangent taken there, which costs the first term; the rounding of the
2061    /// $m$-bit input is the second. The magnitude of the input does not drive the cost.
2062    ///
2063    /// # Panics
2064    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
2065    /// with the given precision (which is the case for every nonzero input).
2066    ///
2067    /// # Examples
2068    /// ```
2069    /// use malachite_base::rounding_modes::RoundingMode::*;
2070    /// use malachite_float::Float;
2071    /// use malachite_q::Rational;
2072    /// use std::cmp::Ordering::*;
2073    ///
2074    /// let (c, o) =
2075    ///     Float::atan_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 5, Floor);
2076    /// assert_eq!(c.to_string(), "0.531");
2077    /// assert_eq!(o, Less);
2078    ///
2079    /// let (c, o) =
2080    ///     Float::atan_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 5, Ceiling);
2081    /// assert_eq!(c.to_string(), "0.562");
2082    /// assert_eq!(o, Greater);
2083    ///
2084    /// let (c, o) =
2085    ///     Float::atan_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 20, Floor);
2086    /// assert_eq!(c.to_string(), "0.54041862");
2087    /// assert_eq!(o, Less);
2088    ///
2089    /// let (c, o) =
2090    ///     Float::atan_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 20, Ceiling);
2091    /// assert_eq!(c.to_string(), "0.54041958");
2092    /// assert_eq!(o, Greater);
2093    /// ```
2094    pub fn atan_rational_prec_round_ref(
2095        x: &Rational,
2096        prec: u64,
2097        rm: RoundingMode,
2098    ) -> (Self, Ordering) {
2099        assert_ne!(prec, 0);
2100        if *x == 0u32 {
2101            // atan(0) = 0, exactly
2102            return (Self::ZERO, Equal);
2103        }
2104        atan_rational_helper(x, prec, rm)
2105    }
2106
2107    /// Computes $\arctan x$, the arctangent of a [`Rational`], rounding the result to the nearest
2108    /// value of the specified precision and returning the result as a [`Float`]. The [`Rational`]
2109    /// is taken by value. An [`Ordering`] is also returned, indicating whether the rounded
2110    /// arctangent is less than, equal to, or greater than the exact arctangent.
2111    ///
2112    /// If the arctangent is equidistant from two [`Float`]s with the specified precision, the
2113    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
2114    /// description of the `Nearest` rounding mode.
2115    ///
2116    /// $$
2117    /// f(x,p) = \arctan x+\varepsilon,
2118    /// $$
2119    /// where $|\varepsilon| \leq 2^{\lfloor\log_2 |\arctan x|\rfloor-p}$ (unless the result
2120    /// underflows; see below).
2121    ///
2122    /// The output has precision `prec`.
2123    ///
2124    /// Special cases:
2125    /// - $f(0,p)=0$.
2126    ///
2127    /// Overflow and underflow:
2128    /// - Since $|\arctan x| < \pi/2$, the result never overflows.
2129    /// - If $0<f(x,p)\leq2^{-2^{30}-1}$, $0.0$ is returned instead.
2130    /// - If $2^{-2^{30}-1}<f(x,p)<2^{-2^{30}}$, $2^{-2^{30}}$ is returned instead.
2131    /// - If $-2^{-2^{30}-1}\leq f(x,p)<0$, $-0.0$ is returned instead.
2132    /// - If $-2^{-2^{30}}<f(x,p)<-2^{-2^{30}-1}$, $-2^{-2^{30}}$ is returned instead.
2133    ///
2134    /// Underflow requires an input of magnitude about $2^{-2^{30}}$ or less: since $|\arctan x| <
2135    /// |x|$ for nonzero $x$, no other input can reach it.
2136    ///
2137    /// If you want to use a rounding mode other than `Nearest`, consider using
2138    /// [`Float::atan_rational_prec_round`] instead.
2139    ///
2140    /// # Worst-case complexity
2141    /// $T(n, m) = O(n (\log n)^3 \log\log n + (n+m) (\log (n+m))^2 \log\log (n+m))$
2142    ///
2143    /// $M(n, m) = O((n+m) \log (n+m))$
2144    ///
2145    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
2146    /// `x.significant_bits()`: the input is rounded once to a working precision of about $n$ bits
2147    /// and its [`Float`] arctangent taken there, which costs the first term; the rounding of the
2148    /// $m$-bit input is the second. The magnitude of the input does not drive the cost.
2149    ///
2150    /// # Panics
2151    /// Panics if `prec` is zero.
2152    ///
2153    /// # Examples
2154    /// ```
2155    /// use malachite_float::Float;
2156    /// use malachite_q::Rational;
2157    /// use std::cmp::Ordering::*;
2158    ///
2159    /// let (c, o) = Float::atan_rational_prec(Rational::from_unsigneds(3u8, 5), 5);
2160    /// assert_eq!(c.to_string(), "0.531");
2161    /// assert_eq!(o, Less);
2162    ///
2163    /// let (c, o) = Float::atan_rational_prec(Rational::from_unsigneds(3u8, 5), 20);
2164    /// assert_eq!(c.to_string(), "0.54041958");
2165    /// assert_eq!(o, Greater);
2166    /// ```
2167    #[inline]
2168    #[allow(clippy::needless_pass_by_value)]
2169    pub fn atan_rational_prec(x: Rational, prec: u64) -> (Self, Ordering) {
2170        Self::atan_rational_prec_round_ref(&x, prec, Nearest)
2171    }
2172
2173    /// Computes $\arctan x$, the arctangent of a [`Rational`], rounding the result to the nearest
2174    /// value of the specified precision and returning the result as a [`Float`]. The [`Rational`]
2175    /// is taken by reference. An [`Ordering`] is also returned, indicating whether the rounded
2176    /// arctangent is less than, equal to, or greater than the exact arctangent.
2177    ///
2178    /// If the arctangent is equidistant from two [`Float`]s with the specified precision, the
2179    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
2180    /// description of the `Nearest` rounding mode.
2181    ///
2182    /// $$
2183    /// f(x,p) = \arctan x+\varepsilon,
2184    /// $$
2185    /// where $|\varepsilon| \leq 2^{\lfloor\log_2 |\arctan x|\rfloor-p}$ (unless the result
2186    /// underflows).
2187    ///
2188    /// The output has precision `prec`.
2189    ///
2190    /// Special cases:
2191    /// - $f(0,p)=0$.
2192    ///
2193    /// See the [`Float::atan_rational_prec`] documentation for information on overflow and
2194    /// underflow.
2195    ///
2196    /// If you want to use a rounding mode other than `Nearest`, consider using
2197    /// [`Float::atan_rational_prec_round_ref`] instead.
2198    ///
2199    /// # Worst-case complexity
2200    /// $T(n, m) = O(n (\log n)^3 \log\log n + (n+m) (\log (n+m))^2 \log\log (n+m))$
2201    ///
2202    /// $M(n, m) = O((n+m) \log (n+m))$
2203    ///
2204    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
2205    /// `x.significant_bits()`: the input is rounded once to a working precision of about $n$ bits
2206    /// and its [`Float`] arctangent taken there, which costs the first term; the rounding of the
2207    /// $m$-bit input is the second. The magnitude of the input does not drive the cost.
2208    ///
2209    /// # Panics
2210    /// Panics if `prec` is zero.
2211    ///
2212    /// # Examples
2213    /// ```
2214    /// use malachite_float::Float;
2215    /// use malachite_q::Rational;
2216    /// use std::cmp::Ordering::*;
2217    ///
2218    /// let (c, o) = Float::atan_rational_prec_ref(&Rational::from_unsigneds(3u8, 5), 5);
2219    /// assert_eq!(c.to_string(), "0.531");
2220    /// assert_eq!(o, Less);
2221    ///
2222    /// let (c, o) = Float::atan_rational_prec_ref(&Rational::from_unsigneds(3u8, 5), 20);
2223    /// assert_eq!(c.to_string(), "0.54041958");
2224    /// assert_eq!(o, Greater);
2225    /// ```
2226    #[inline]
2227    pub fn atan_rational_prec_ref(x: &Rational, prec: u64) -> (Self, Ordering) {
2228        Self::atan_rational_prec_round_ref(x, prec, Nearest)
2229    }
2230
2231    /// Computes $\arctan(x)u/(2\pi)$, the arctangent of a [`Rational`] measured in $u$ths of a
2232    /// turn, rounding the result to the specified precision and with the specified rounding mode
2233    /// and returning the result as a [`Float`]. The [`Rational`] is taken by value. An [`Ordering`]
2234    /// is also returned, indicating whether the rounded arctangent is less than, equal to, or
2235    /// greater than the exact arctangent.
2236    ///
2237    /// See [`RoundingMode`] for a description of the possible rounding modes.
2238    ///
2239    /// $$
2240    /// f(x,u,p,m) = \arctan(x)u/(2\pi)+\varepsilon.
2241    /// $$
2242    /// - If $x$ is zero, $u = 0$, or $|x|$ is 1, $\varepsilon$ may be ignored or assumed to be 0.
2243    /// - Otherwise, if $m$ is not `Nearest`, then $|\varepsilon| < 2^{\lfloor\log_2
2244    ///   |\arctan(x)u/(2\pi)|\rfloor-p+1}$.
2245    /// - Otherwise, if $m$ is `Nearest`, then $|\varepsilon| \leq 2^{\lfloor\log_2
2246    ///   |\arctan(x)u/(2\pi)|\rfloor-p}$.
2247    ///
2248    /// The output has precision `prec`.
2249    ///
2250    /// Special cases:
2251    /// - $f(0,u,p,m)=0.0$
2252    /// - $f(x,0,p,m)=\pm0.0$, with the sign of $x$, so that the function stays odd
2253    /// - $f(\pm1,u,p,m)=\pm u/8$, an eighth of a turn
2254    ///
2255    /// These are the only exact cases, and the eighth turn is exact only when $p$ is large enough
2256    /// to hold it.
2257    ///
2258    /// Underflow:
2259    /// - If $0<f(x,u,p,m)<2^{-2^{30}}$, and $m$ is `Floor` or `Down`, $0.0$ is returned instead.
2260    /// - If $0<f(x,u,p,m)<2^{-2^{30}}$, and $m$ is `Ceiling` or `Up`, $2^{-2^{30}}$ is returned
2261    ///   instead.
2262    /// - If $0<f(x,u,p,m)\leq2^{-2^{30}-1}$, and $m$ is `Nearest`, $0.0$ is returned instead.
2263    /// - If $2^{-2^{30}-1}<f(x,u,p,m)<2^{-2^{30}}$, and $m$ is `Nearest`, $2^{-2^{30}}$ is returned
2264    ///   instead.
2265    /// - The negative cases mirror these, since the function is odd.
2266    ///
2267    /// Overflow is not possible, since $|f(x,u,p,m)| < u/4 < 2^{62}$. Underflow requires a tiny $x$
2268    /// together with a small $u$, since the result is about $xu/(2\pi)$ there. Unlike the [`Float`]
2269    /// case, $x$ itself may be far below the bottom of the exponent range.
2270    ///
2271    /// If you know you'll be using `Nearest`, consider using
2272    /// [`Float::atan_with_period_rational_prec`] instead.
2273    ///
2274    /// # Worst-case complexity
2275    /// $T(n, m) = O(n (\log n)^3 \log\log n + (n+m) (\log (n+m))^2 \log\log (n+m))$
2276    ///
2277    /// $M(n, m) = O((n+m) \log (n+m))$
2278    ///
2279    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
2280    /// `x.significant_bits()`: the arctangent is taken at a working precision of about $n$ bits and
2281    /// scaled by $u/(2\pi)$, which needs $\pi$ to that many bits, and both cost the first term; the
2282    /// second covers the $m$-bit input. The magnitude of the input does not drive the cost.
2283    ///
2284    /// # Panics
2285    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
2286    /// with the given precision (which is the case unless $x$ is zero, $u$ is zero, or $|x|$ is 1
2287    /// and $p$ is large enough to hold an eighth of a turn).
2288    ///
2289    /// # Examples
2290    /// ```
2291    /// use malachite_base::num::basic::traits::One;
2292    /// use malachite_base::rounding_modes::RoundingMode::*;
2293    /// use malachite_float::Float;
2294    /// use malachite_q::Rational;
2295    /// use std::cmp::Ordering::*;
2296    ///
2297    /// let (t, o) = Float::atan_with_period_rational_prec_round(Rational::ONE, 360, 10, Exact);
2298    /// assert_eq!(t.to_string(), "45.000");
2299    /// assert_eq!(o, Equal);
2300    ///
2301    /// let (t, o) = Float::atan_with_period_rational_prec_round(
2302    ///     Rational::from_unsigneds(3u8, 5),
2303    ///     360,
2304    ///     10,
2305    ///     Floor,
2306    /// );
2307    /// assert_eq!(t.to_string(), "30.938");
2308    /// assert_eq!(o, Less);
2309    ///
2310    /// let (t, o) = Float::atan_with_period_rational_prec_round(
2311    ///     Rational::from_unsigneds(3u8, 5),
2312    ///     360,
2313    ///     10,
2314    ///     Ceiling,
2315    /// );
2316    /// assert_eq!(t.to_string(), "30.969");
2317    /// assert_eq!(o, Greater);
2318    /// ```
2319    #[inline]
2320    #[allow(clippy::needless_pass_by_value)]
2321    pub fn atan_with_period_rational_prec_round(
2322        x: Rational,
2323        u: u64,
2324        prec: u64,
2325        rm: RoundingMode,
2326    ) -> (Self, Ordering) {
2327        Self::atan_with_period_rational_prec_round_ref(&x, u, prec, rm)
2328    }
2329
2330    /// Computes $\arctan(x)u/(2\pi)$, the arctangent of a [`Rational`] measured in $u$ths of a
2331    /// turn, rounding the result to the specified precision and with the specified rounding mode
2332    /// and returning the result as a [`Float`]. The [`Rational`] is taken by reference. An
2333    /// [`Ordering`] is also returned, indicating whether the rounded arctangent is less than, equal
2334    /// to, or greater than the exact arctangent.
2335    ///
2336    /// See [`Float::atan_with_period_rational_prec_round`] for the error bounds, the special cases,
2337    /// underflow, and the complexity; this function behaves the same way.
2338    ///
2339    /// # Panics
2340    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
2341    /// with the given precision.
2342    ///
2343    /// # Examples
2344    /// ```
2345    /// use malachite_base::num::basic::traits::One;
2346    /// use malachite_base::rounding_modes::RoundingMode::*;
2347    /// use malachite_float::Float;
2348    /// use malachite_q::Rational;
2349    /// use std::cmp::Ordering::*;
2350    ///
2351    /// let (t, o) =
2352    ///     Float::atan_with_period_rational_prec_round_ref(&Rational::ONE, 360, 10, Exact);
2353    /// assert_eq!(t.to_string(), "45.000");
2354    /// assert_eq!(o, Equal);
2355    ///
2356    /// let (t, o) = Float::atan_with_period_rational_prec_round_ref(
2357    ///     &Rational::from_unsigneds(3u8, 5),
2358    ///     360,
2359    ///     10,
2360    ///     Floor,
2361    /// );
2362    /// assert_eq!(t.to_string(), "30.938");
2363    /// assert_eq!(o, Less);
2364    /// ```
2365    pub fn atan_with_period_rational_prec_round_ref(
2366        x: &Rational,
2367        u: u64,
2368        prec: u64,
2369        rm: RoundingMode,
2370    ) -> (Self, Ordering) {
2371        assert_ne!(prec, 0);
2372        // atanu(0, u) = 0, and atanu(x, 0) = 0 with the sign of x, so that the function stays odd;
2373        // a `Rational` zero has no sign, so the first case gives a positive zero
2374        if *x == 0u32 || u == 0 {
2375            return (
2376                if *x < 0u32 {
2377                    Self::NEGATIVE_ZERO
2378                } else {
2379                    Self::ZERO
2380                },
2381                Equal,
2382            );
2383        }
2384        atan_with_period_rational_helper(x, u, prec, rm)
2385    }
2386
2387    /// Computes $\arctan(x)u/(2\pi)$, the arctangent of a [`Rational`] measured in $u$ths of a
2388    /// turn, rounding the result to the nearest value of the specified precision and returning the
2389    /// result as a [`Float`]. The [`Rational`] is taken by value. An [`Ordering`] is also returned,
2390    /// indicating whether the rounded arctangent is less than, equal to, or greater than the exact
2391    /// arctangent.
2392    ///
2393    /// If the arctangent is equidistant from two [`Float`]s with the specified precision, the
2394    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
2395    /// description of the `Nearest` rounding mode.
2396    ///
2397    /// $$
2398    /// f(x,u,p) = \arctan(x)u/(2\pi)+\varepsilon,
2399    /// $$
2400    /// where $|\varepsilon| \leq 2^{\lfloor\log_2 |\arctan(x)u/(2\pi)|\rfloor-p}$ (unless the
2401    /// result underflows, or is one of the exact cases below).
2402    ///
2403    /// The output has precision `prec`.
2404    ///
2405    /// Special cases:
2406    /// - $f(0,u,p)=0.0$
2407    /// - $f(x,0,p)=\pm0.0$, with the sign of $x$, so that the function stays odd
2408    /// - $f(\pm1,u,p)=\pm u/8$, an eighth of a turn
2409    ///
2410    /// See the [`Float::atan_with_period_rational_prec_round`] documentation for information on
2411    /// overflow and underflow.
2412    ///
2413    /// If you want to use a rounding mode other than `Nearest`, consider using
2414    /// [`Float::atan_with_period_rational_prec_round`] instead.
2415    ///
2416    /// # Worst-case complexity
2417    /// $T(n, m) = O(n (\log n)^3 \log\log n + (n+m) (\log (n+m))^2 \log\log (n+m))$
2418    ///
2419    /// $M(n, m) = O((n+m) \log (n+m))$
2420    ///
2421    /// where $T$ is time, $M$ is additional memory, $n$ is `prec`, and $m$ is
2422    /// `x.significant_bits()`: the arctangent is taken at a working precision of about $n$ bits and
2423    /// scaled by $u/(2\pi)$, which needs $\pi$ to that many bits, and both cost the first term; the
2424    /// second covers the $m$-bit input. The magnitude of the input does not drive the cost.
2425    ///
2426    /// # Panics
2427    /// Panics if `prec` is zero.
2428    ///
2429    /// # Examples
2430    /// ```
2431    /// use malachite_float::Float;
2432    /// use malachite_q::Rational;
2433    /// use std::cmp::Ordering::*;
2434    ///
2435    /// let (t, o) =
2436    ///     Float::atan_with_period_rational_prec(Rational::from_unsigneds(3u8, 5), 360, 10);
2437    /// assert_eq!(t.to_string(), "30.969");
2438    /// assert_eq!(o, Greater);
2439    ///
2440    /// let (t, o) =
2441    ///     Float::atan_with_period_rational_prec(Rational::from_unsigneds(3u8, 5), 360, 20);
2442    /// assert_eq!(t.to_string(), "30.963745");
2443    /// assert_eq!(o, Less);
2444    /// ```
2445    #[inline]
2446    #[allow(clippy::needless_pass_by_value)]
2447    pub fn atan_with_period_rational_prec(x: Rational, u: u64, prec: u64) -> (Self, Ordering) {
2448        Self::atan_with_period_rational_prec_round_ref(&x, u, prec, Nearest)
2449    }
2450
2451    /// Computes $\arctan(x)u/(2\pi)$, the arctangent of a [`Rational`] measured in $u$ths of a
2452    /// turn, rounding the result to the nearest value of the specified precision and returning the
2453    /// result as a [`Float`]. The [`Rational`] is taken by reference. An [`Ordering`] is also
2454    /// returned, indicating whether the rounded arctangent is less than, equal to, or greater than
2455    /// the exact arctangent.
2456    ///
2457    /// See [`Float::atan_with_period_rational_prec`] for the error bounds, the special cases,
2458    /// underflow, and the complexity; this function behaves the same way.
2459    ///
2460    /// # Panics
2461    /// Panics if `prec` is zero.
2462    ///
2463    /// # Examples
2464    /// ```
2465    /// use malachite_float::Float;
2466    /// use malachite_q::Rational;
2467    /// use std::cmp::Ordering::*;
2468    ///
2469    /// let (t, o) =
2470    ///     Float::atan_with_period_rational_prec_ref(&Rational::from_unsigneds(3u8, 5), 360, 10);
2471    /// assert_eq!(t.to_string(), "30.969");
2472    /// assert_eq!(o, Greater);
2473    ///
2474    /// let (t, o) =
2475    ///     Float::atan_with_period_rational_prec_ref(&Rational::from_unsigneds(3u8, 5), 360, 20);
2476    /// assert_eq!(t.to_string(), "30.963745");
2477    /// assert_eq!(o, Less);
2478    /// ```
2479    #[inline]
2480    pub fn atan_with_period_rational_prec_ref(x: &Rational, u: u64, prec: u64) -> (Self, Ordering) {
2481        Self::atan_with_period_rational_prec_round_ref(x, u, prec, Nearest)
2482    }
2483
2484    /// Computes $\arctan(x)/\pi$, the arctangent of a [`Float`] measured in half-turns, rounding
2485    /// the result to the specified precision and with the specified rounding mode. The [`Float`] is
2486    /// taken by value. An [`Ordering`] is also returned, indicating whether the rounded arctangent
2487    /// is less than, equal to, or greater than the exact arctangent. Although `NaN`s are not
2488    /// comparable to any [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
2489    ///
2490    /// This is `atan_with_period` with a period of 2: see [`Float::atan_with_period_prec_round`]
2491    /// for the error bounds, the special cases, underflow, and the complexity, with $u = 2$. An
2492    /// infinite input gives $\pm1/2$ and an input of $\pm1$ gives $\pm1/4$, both exact at every
2493    /// precision, since a half and a quarter need only one bit; a zero input gives $\pm0.0$. Those
2494    /// are the only exact cases. Overflow is not possible, since $|\arctan(x)/\pi| < 1/2$.
2495    ///
2496    /// # Panics
2497    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
2498    /// with the given precision.
2499    ///
2500    /// # Examples
2501    /// ```
2502    /// use malachite_base::num::basic::traits::One;
2503    /// use malachite_base::rounding_modes::RoundingMode::*;
2504    /// use malachite_float::Float;
2505    /// use std::cmp::Ordering::*;
2506    ///
2507    /// let (t, o) = Float::from(0.1f64).atan_pi_prec_round(10, Floor);
2508    /// assert_eq!(t.to_string(), "0.031677");
2509    /// assert_eq!(o, Less);
2510    ///
2511    /// let (t, o) = Float::from(0.1f64).atan_pi_prec_round(10, Ceiling);
2512    /// assert_eq!(t.to_string(), "0.031738");
2513    /// assert_eq!(o, Greater);
2514    ///
2515    /// // an input of 1 gives an eighth of a turn, which is a quarter of a half-turn, exactly
2516    /// let (t, o) = Float::ONE.atan_pi_prec_round(10, Exact);
2517    /// assert_eq!(t.to_string(), "0.25000");
2518    /// assert_eq!(o, Equal);
2519    /// ```
2520    #[inline]
2521    pub fn atan_pi_prec_round(self, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
2522        self.atan_with_period_prec_round(2, prec, rm)
2523    }
2524
2525    /// Computes $\arctan(x)/\pi$, the arctangent of a [`Float`] measured in half-turns, rounding
2526    /// the result to the specified precision and with the specified rounding mode. The [`Float`] is
2527    /// taken by reference. An [`Ordering`] is also returned, indicating whether the rounded
2528    /// arctangent is less than, equal to, or greater than the exact arctangent. Although `NaN`s are
2529    /// not comparable to any [`Float`], whenever this function returns a `NaN` it also returns
2530    /// `Equal`.
2531    ///
2532    /// This is `atan_with_period` with a period of 2: see
2533    /// [`Float::atan_with_period_prec_round_ref`] for the error bounds, the special cases,
2534    /// underflow, and the complexity, with $u = 2$. An infinite input gives $\pm1/2$ and an input
2535    /// of $\pm1$ gives $\pm1/4$, both exact at every precision, since a half and a quarter need
2536    /// only one bit; a zero input gives $\pm0.0$. Those are the only exact cases. Overflow is not
2537    /// possible, since $|\arctan(x)/\pi| < 1/2$.
2538    ///
2539    /// # Panics
2540    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
2541    /// with the given precision.
2542    ///
2543    /// # Examples
2544    /// ```
2545    /// use malachite_base::num::basic::traits::One;
2546    /// use malachite_base::rounding_modes::RoundingMode::*;
2547    /// use malachite_float::Float;
2548    /// use std::cmp::Ordering::*;
2549    ///
2550    /// let (t, o) = (Float::from(0.1f64)).atan_pi_prec_round_ref(10, Floor);
2551    /// assert_eq!(t.to_string(), "0.031677");
2552    /// assert_eq!(o, Less);
2553    ///
2554    /// let (t, o) = (Float::from(0.1f64)).atan_pi_prec_round_ref(10, Ceiling);
2555    /// assert_eq!(t.to_string(), "0.031738");
2556    /// assert_eq!(o, Greater);
2557    ///
2558    /// // an input of 1 gives an eighth of a turn, which is a quarter of a half-turn, exactly
2559    /// let (t, o) = (&Float::ONE).atan_pi_prec_round_ref(10, Exact);
2560    /// assert_eq!(t.to_string(), "0.25000");
2561    /// assert_eq!(o, Equal);
2562    /// ```
2563    #[inline]
2564    pub fn atan_pi_prec_round_ref(&self, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
2565        self.atan_with_period_prec_round_ref(2, prec, rm)
2566    }
2567
2568    /// Computes $\arctan(x)/\pi$, the arctangent of a [`Float`] measured in half-turns, rounding
2569    /// the result to the nearest value of the specified precision. The [`Float`] is taken by value.
2570    /// An [`Ordering`] is also returned, indicating whether the rounded arctangent is less than,
2571    /// equal to, or greater than the exact arctangent. Although `NaN`s are not comparable to any
2572    /// [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
2573    ///
2574    /// This is `atan_with_period` with a period of 2: see [`Float::atan_with_period_prec`] for the
2575    /// error bounds, the special cases, underflow, and the complexity, with $u = 2$. An infinite
2576    /// input gives $\pm1/2$ and an input of $\pm1$ gives $\pm1/4$, both exact at every precision,
2577    /// since a half and a quarter need only one bit; a zero input gives $\pm0.0$. Those are the
2578    /// only exact cases. Overflow is not possible, since $|\arctan(x)/\pi| < 1/2$.
2579    ///
2580    /// # Panics
2581    /// Panics if `prec` is zero.
2582    ///
2583    /// # Examples
2584    /// ```
2585    /// use malachite_float::Float;
2586    /// use std::cmp::Ordering::*;
2587    ///
2588    /// let (t, o) = Float::from(0.1f64).atan_pi_prec(10);
2589    /// assert_eq!(t.to_string(), "0.031738");
2590    /// assert_eq!(o, Greater);
2591    ///
2592    /// let (t, o) = Float::from(0.1f64).atan_pi_prec(53);
2593    /// assert_eq!(t.to_string(), "0.031725517430553574");
2594    /// assert_eq!(o, Greater);
2595    /// ```
2596    #[inline]
2597    pub fn atan_pi_prec(self, prec: u64) -> (Self, Ordering) {
2598        self.atan_with_period_prec(2, prec)
2599    }
2600
2601    /// Computes $\arctan(x)/\pi$, the arctangent of a [`Float`] measured in half-turns, rounding
2602    /// the result to the nearest value of the specified precision. The [`Float`] is taken by
2603    /// reference. An [`Ordering`] is also returned, indicating whether the rounded arctangent is
2604    /// less than, equal to, or greater than the exact arctangent. Although `NaN`s are not
2605    /// comparable to any [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
2606    ///
2607    /// This is `atan_with_period` with a period of 2: see [`Float::atan_with_period_prec_ref`] for
2608    /// the error bounds, the special cases, underflow, and the complexity, with $u = 2$. An
2609    /// infinite input gives $\pm1/2$ and an input of $\pm1$ gives $\pm1/4$, both exact at every
2610    /// precision, since a half and a quarter need only one bit; a zero input gives $\pm0.0$. Those
2611    /// are the only exact cases. Overflow is not possible, since $|\arctan(x)/\pi| < 1/2$.
2612    ///
2613    /// # Panics
2614    /// Panics if `prec` is zero.
2615    ///
2616    /// # Examples
2617    /// ```
2618    /// use malachite_float::Float;
2619    /// use std::cmp::Ordering::*;
2620    ///
2621    /// let (t, o) = (Float::from(0.1f64)).atan_pi_prec_ref(10);
2622    /// assert_eq!(t.to_string(), "0.031738");
2623    /// assert_eq!(o, Greater);
2624    ///
2625    /// let (t, o) = (Float::from(0.1f64)).atan_pi_prec_ref(53);
2626    /// assert_eq!(t.to_string(), "0.031725517430553574");
2627    /// assert_eq!(o, Greater);
2628    /// ```
2629    #[inline]
2630    pub fn atan_pi_prec_ref(&self, prec: u64) -> (Self, Ordering) {
2631        self.atan_with_period_prec_ref(2, prec)
2632    }
2633
2634    /// Computes $\arctan(x)/\pi$, the arctangent of a [`Float`] measured in half-turns, rounding
2635    /// the result with the specified rounding mode. The precision of the output is the precision of
2636    /// the input. The [`Float`] is taken by value. An [`Ordering`] is also returned, indicating
2637    /// whether the rounded arctangent is less than, equal to, or greater than the exact arctangent.
2638    /// Although `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN`
2639    /// it also returns `Equal`.
2640    ///
2641    /// This is `atan_with_period` with a period of 2: see [`Float::atan_with_period_round`] for the
2642    /// error bounds, the special cases, underflow, and the complexity, with $u = 2$. An infinite
2643    /// input gives $\pm1/2$ and an input of $\pm1$ gives $\pm1/4$, both exact at every precision,
2644    /// since a half and a quarter need only one bit; a zero input gives $\pm0.0$. Those are the
2645    /// only exact cases. Overflow is not possible, since $|\arctan(x)/\pi| < 1/2$.
2646    ///
2647    /// # Panics
2648    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the input
2649    /// precision.
2650    ///
2651    /// # Examples
2652    /// ```
2653    /// use malachite_base::rounding_modes::RoundingMode::*;
2654    /// use malachite_float::Float;
2655    /// use std::cmp::Ordering::*;
2656    ///
2657    /// let (t, o) = Float::from(0.1f64).atan_pi_round(Floor);
2658    /// assert_eq!(t.to_string(), "0.031725517430553560");
2659    /// assert_eq!(o, Less);
2660    ///
2661    /// let (t, o) = Float::from(0.1f64).atan_pi_round(Nearest);
2662    /// assert_eq!(t.to_string(), "0.031725517430553574");
2663    /// assert_eq!(o, Greater);
2664    /// ```
2665    #[inline]
2666    pub fn atan_pi_round(self, rm: RoundingMode) -> (Self, Ordering) {
2667        self.atan_with_period_round(2, rm)
2668    }
2669
2670    /// Computes $\arctan(x)/\pi$, the arctangent of a [`Float`] measured in half-turns, rounding
2671    /// the result with the specified rounding mode. The precision of the output is the precision of
2672    /// the input. The [`Float`] is taken by reference. An [`Ordering`] is also returned, indicating
2673    /// whether the rounded arctangent is less than, equal to, or greater than the exact arctangent.
2674    /// Although `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN`
2675    /// it also returns `Equal`.
2676    ///
2677    /// This is `atan_with_period` with a period of 2: see [`Float::atan_with_period_round_ref`] for
2678    /// the error bounds, the special cases, underflow, and the complexity, with $u = 2$. An
2679    /// infinite input gives $\pm1/2$ and an input of $\pm1$ gives $\pm1/4$, both exact at every
2680    /// precision, since a half and a quarter need only one bit; a zero input gives $\pm0.0$. Those
2681    /// are the only exact cases. Overflow is not possible, since $|\arctan(x)/\pi| < 1/2$.
2682    ///
2683    /// # Panics
2684    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the input
2685    /// precision.
2686    ///
2687    /// # Examples
2688    /// ```
2689    /// use malachite_base::rounding_modes::RoundingMode::*;
2690    /// use malachite_float::Float;
2691    /// use std::cmp::Ordering::*;
2692    ///
2693    /// let (t, o) = (Float::from(0.1f64)).atan_pi_round_ref(Floor);
2694    /// assert_eq!(t.to_string(), "0.031725517430553560");
2695    /// assert_eq!(o, Less);
2696    ///
2697    /// let (t, o) = (Float::from(0.1f64)).atan_pi_round_ref(Nearest);
2698    /// assert_eq!(t.to_string(), "0.031725517430553574");
2699    /// assert_eq!(o, Greater);
2700    /// ```
2701    #[inline]
2702    pub fn atan_pi_round_ref(&self, rm: RoundingMode) -> (Self, Ordering) {
2703        self.atan_with_period_round_ref(2, rm)
2704    }
2705
2706    /// Computes $\arctan(x)/\pi$, the arctangent of a [`Float`] measured in half-turns, rounding
2707    /// the result to the precision of the input and to the nearest [`Float`]. The [`Float`] is
2708    /// taken by value.
2709    ///
2710    /// If the arctangent is equidistant from two [`Float`]s with the precision of the input, the
2711    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
2712    /// description of the `Nearest` rounding mode.
2713    ///
2714    /// This is `atan_with_period` with a period of 2: see [`Float::atan_with_period`] for the error
2715    /// bounds, the special cases, underflow, and the complexity, with $u = 2$. An infinite input
2716    /// gives $\pm1/2$ and an input of $\pm1$ gives $\pm1/4$, both exact at every precision, since a
2717    /// half and a quarter need only one bit; a zero input gives $\pm0.0$. Those are the only exact
2718    /// cases. Overflow is not possible, since $|\arctan(x)/\pi| < 1/2$.
2719    ///
2720    /// If you want to use a rounding mode other than `Nearest`, consider using
2721    /// [`Float::atan_pi_round`] instead. If you want to specify an output precision, consider using
2722    /// [`Float::atan_pi_prec`]. If you want both of these things, consider using
2723    /// [`Float::atan_pi_prec_round`].
2724    ///
2725    /// # Examples
2726    /// ```
2727    /// use malachite_float::Float;
2728    ///
2729    /// let t = Float::from(0.1f64).atan_pi();
2730    /// assert_eq!(t.to_string(), "0.031725517430553574");
2731    ///
2732    /// assert_eq!(Float::from(0.5f64).atan_pi().to_string(), "0.12");
2733    /// ```
2734    #[inline]
2735    pub fn atan_pi(self) -> Self {
2736        let prec = self.significant_bits();
2737        self.atan_pi_prec(prec).0
2738    }
2739
2740    /// Computes $\arctan(x)/\pi$, the arctangent of a [`Float`] measured in half-turns, rounding
2741    /// the result to the precision of the input and to the nearest [`Float`]. The [`Float`] is
2742    /// taken by reference.
2743    ///
2744    /// If the arctangent is equidistant from two [`Float`]s with the precision of the input, the
2745    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
2746    /// description of the `Nearest` rounding mode.
2747    ///
2748    /// This is `atan_with_period` with a period of 2: see [`Float::atan_with_period`] for the error
2749    /// bounds, the special cases, underflow, and the complexity, with $u = 2$. An infinite input
2750    /// gives $\pm1/2$ and an input of $\pm1$ gives $\pm1/4$, both exact at every precision, since a
2751    /// half and a quarter need only one bit; a zero input gives $\pm0.0$. Those are the only exact
2752    /// cases. Overflow is not possible, since $|\arctan(x)/\pi| < 1/2$.
2753    ///
2754    /// If you want to use a rounding mode other than `Nearest`, consider using
2755    /// [`Float::atan_pi_round_ref`] instead. If you want to specify an output precision, consider
2756    /// using [`Float::atan_pi_prec_ref`]. If you want both of these things, consider using
2757    /// [`Float::atan_pi_prec_round_ref`].
2758    ///
2759    /// # Examples
2760    /// ```
2761    /// use malachite_float::Float;
2762    ///
2763    /// let t = (&Float::from(0.1f64)).atan_pi_ref();
2764    /// assert_eq!(t.to_string(), "0.031725517430553574");
2765    /// ```
2766    #[inline]
2767    pub fn atan_pi_ref(&self) -> Self {
2768        self.atan_pi_prec_ref(self.significant_bits()).0
2769    }
2770
2771    /// Computes $\arctan(x)/\pi$, the arctangent of a [`Float`] measured in half-turns, rounding
2772    /// the result to the specified precision and with the specified rounding mode. The [`Float`] is
2773    /// replaced by the result, and an [`Ordering`] is returned, indicating whether the rounded
2774    /// arctangent is less than, equal to, or greater than the exact arctangent. Although `NaN`s are
2775    /// not comparable to any [`Float`], whenever this function sets a `NaN` it also returns
2776    /// `Equal`.
2777    ///
2778    /// This is `atan_with_period` with a period of 2: see
2779    /// [`Float::atan_with_period_prec_round_assign`] for the error bounds, the special cases,
2780    /// underflow, and the complexity, with $u = 2$. An infinite input gives $\pm1/2$ and an input
2781    /// of $\pm1$ gives $\pm1/4$, both exact at every precision, since a half and a quarter need
2782    /// only one bit; a zero input gives $\pm0.0$. Those are the only exact cases. Overflow is not
2783    /// possible, since $|\arctan(x)/\pi| < 1/2$.
2784    ///
2785    /// # Panics
2786    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
2787    /// with the given precision.
2788    ///
2789    /// # Examples
2790    /// ```
2791    /// use malachite_base::rounding_modes::RoundingMode::*;
2792    /// use malachite_float::Float;
2793    /// use std::cmp::Ordering::*;
2794    ///
2795    /// let mut x = Float::from(0.1f64);
2796    /// assert_eq!(x.atan_pi_prec_round_assign(10, Floor), Less);
2797    /// assert_eq!(x.to_string(), "0.031677");
2798    ///
2799    /// let mut x = Float::from(0.1f64);
2800    /// assert_eq!(x.atan_pi_prec_round_assign(10, Ceiling), Greater);
2801    /// assert_eq!(x.to_string(), "0.031738");
2802    /// ```
2803    #[inline]
2804    pub fn atan_pi_prec_round_assign(&mut self, prec: u64, rm: RoundingMode) -> Ordering {
2805        self.atan_with_period_prec_round_assign(2, prec, rm)
2806    }
2807
2808    /// Computes $\arctan(x)/\pi$, the arctangent of a [`Float`] measured in half-turns, rounding
2809    /// the result to the nearest value of the specified precision. The [`Float`] is replaced by the
2810    /// result, and an [`Ordering`] is returned, indicating whether the rounded arctangent is less
2811    /// than, equal to, or greater than the exact arctangent. Although `NaN`s are not comparable to
2812    /// any [`Float`], whenever this function sets a `NaN` it also returns `Equal`.
2813    ///
2814    /// This is `atan_with_period` with a period of 2: see [`Float::atan_with_period_prec_assign`]
2815    /// for the error bounds, the special cases, underflow, and the complexity, with $u = 2$. An
2816    /// infinite input gives $\pm1/2$ and an input of $\pm1$ gives $\pm1/4$, both exact at every
2817    /// precision, since a half and a quarter need only one bit; a zero input gives $\pm0.0$. Those
2818    /// are the only exact cases. Overflow is not possible, since $|\arctan(x)/\pi| < 1/2$.
2819    ///
2820    /// # Panics
2821    /// Panics if `prec` is zero.
2822    ///
2823    /// # Examples
2824    /// ```
2825    /// use malachite_float::Float;
2826    /// use std::cmp::Ordering::*;
2827    ///
2828    /// let mut x = Float::from(0.1f64);
2829    /// assert_eq!(x.atan_pi_prec_assign(10), Greater);
2830    /// assert_eq!(x.to_string(), "0.031738");
2831    /// ```
2832    #[inline]
2833    pub fn atan_pi_prec_assign(&mut self, prec: u64) -> Ordering {
2834        self.atan_with_period_prec_assign(2, prec)
2835    }
2836
2837    /// Computes $\arctan(x)/\pi$, the arctangent of a [`Float`] measured in half-turns, rounding
2838    /// the result with the specified rounding mode. The precision of the output is the precision of
2839    /// the input. The [`Float`] is replaced by the result, and an [`Ordering`] is returned,
2840    /// indicating whether the rounded arctangent is less than, equal to, or greater than the exact
2841    /// arctangent. Although `NaN`s are not comparable to any [`Float`], whenever this function sets
2842    /// a `NaN` it also returns `Equal`.
2843    ///
2844    /// This is `atan_with_period` with a period of 2: see [`Float::atan_with_period_round_assign`]
2845    /// for the error bounds, the special cases, underflow, and the complexity, with $u = 2$. An
2846    /// infinite input gives $\pm1/2$ and an input of $\pm1$ gives $\pm1/4$, both exact at every
2847    /// precision, since a half and a quarter need only one bit; a zero input gives $\pm0.0$. Those
2848    /// are the only exact cases. Overflow is not possible, since $|\arctan(x)/\pi| < 1/2$.
2849    ///
2850    /// # Panics
2851    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the input
2852    /// precision.
2853    ///
2854    /// # Examples
2855    /// ```
2856    /// use malachite_base::rounding_modes::RoundingMode::*;
2857    /// use malachite_float::Float;
2858    /// use std::cmp::Ordering::*;
2859    ///
2860    /// let mut x = Float::from(0.1f64);
2861    /// assert_eq!(x.atan_pi_round_assign(Floor), Less);
2862    /// assert_eq!(x.to_string(), "0.031725517430553560");
2863    /// ```
2864    #[inline]
2865    pub fn atan_pi_round_assign(&mut self, rm: RoundingMode) -> Ordering {
2866        self.atan_with_period_round_assign(2, rm)
2867    }
2868
2869    /// Computes $\arctan(x)/\pi$, the arctangent of a [`Float`] measured in half-turns, rounding
2870    /// the result to the precision of the input and to the nearest [`Float`]. The [`Float`] is
2871    /// replaced by the result.
2872    ///
2873    /// If the arctangent is equidistant from two [`Float`]s with the precision of the input, the
2874    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
2875    /// description of the `Nearest` rounding mode.
2876    ///
2877    /// This is `atan_with_period` with a period of 2: see [`Float::atan_with_period`] for the error
2878    /// bounds, the special cases, underflow, and the complexity, with $u = 2$. An infinite input
2879    /// gives $\pm1/2$ and an input of $\pm1$ gives $\pm1/4$, both exact at every precision, since a
2880    /// half and a quarter need only one bit; a zero input gives $\pm0.0$. Those are the only exact
2881    /// cases. Overflow is not possible, since $|\arctan(x)/\pi| < 1/2$.
2882    ///
2883    /// If you want to use a rounding mode other than `Nearest`, consider using
2884    /// [`Float::atan_pi_round_assign`] instead. If you want to specify an output precision,
2885    /// consider using [`Float::atan_pi_prec_assign`]. If you want both of these things, consider
2886    /// using [`Float::atan_pi_prec_round_assign`].
2887    ///
2888    /// # Examples
2889    /// ```
2890    /// use malachite_float::Float;
2891    ///
2892    /// let mut x = Float::from(0.1f64);
2893    /// x.atan_pi_assign();
2894    /// assert_eq!(x.to_string(), "0.031725517430553574");
2895    /// ```
2896    #[inline]
2897    pub fn atan_pi_assign(&mut self) {
2898        let prec = self.significant_bits();
2899        self.atan_pi_prec_assign(prec);
2900    }
2901
2902    /// Computes $\arctan(x)/\pi$, the arctangent of a [`Rational`] measured in half-turns, rounding
2903    /// the result to the specified precision and with the specified rounding mode and returning the
2904    /// result as a [`Float`]. The [`Rational`] is taken by value. An [`Ordering`] is also returned,
2905    /// indicating whether the rounded arctangent is less than, equal to, or greater than the exact
2906    /// arctangent.
2907    ///
2908    /// This is `atan_with_period_rational` with a period of 2: see
2909    /// [`Float::atan_with_period_rational_prec_round`] for the error bounds, the special cases,
2910    /// underflow, and the complexity, with $u = 2$. An input of $\pm1$ gives $\pm1/4$ and a zero
2911    /// input gives $0.0$, both exact at every precision; those are the only exact cases. Overflow
2912    /// is not possible, since $|\arctan(x)/\pi| < 1/2$.
2913    ///
2914    /// # Panics
2915    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
2916    /// with the given precision.
2917    ///
2918    /// # Examples
2919    /// ```
2920    /// use malachite_base::num::basic::traits::One;
2921    /// use malachite_base::rounding_modes::RoundingMode::*;
2922    /// use malachite_float::Float;
2923    /// use malachite_q::Rational;
2924    /// use std::cmp::Ordering::*;
2925    ///
2926    /// let (t, o) =
2927    ///     Float::atan_pi_rational_prec_round(Rational::from_unsigneds(1u8, 7), 10, Floor);
2928    /// assert_eq!(t.to_string(), "0.045166");
2929    /// assert_eq!(o, Less);
2930    ///
2931    /// // an input of 1 gives a quarter of a half-turn, exactly
2932    /// let (t, o) = Float::atan_pi_rational_prec_round(Rational::ONE, 10, Exact);
2933    /// assert_eq!(t.to_string(), "0.25000");
2934    /// assert_eq!(o, Equal);
2935    /// ```
2936    #[inline]
2937    #[allow(clippy::needless_pass_by_value)]
2938    pub fn atan_pi_rational_prec_round(
2939        x: Rational,
2940        prec: u64,
2941        rm: RoundingMode,
2942    ) -> (Self, Ordering) {
2943        Self::atan_with_period_rational_prec_round_ref(&x, 2, prec, rm)
2944    }
2945
2946    /// Computes $\arctan(x)/\pi$, the arctangent of a [`Rational`] measured in half-turns, rounding
2947    /// the result to the specified precision and with the specified rounding mode and returning the
2948    /// result as a [`Float`]. The [`Rational`] is taken by reference. An [`Ordering`] is also
2949    /// returned, indicating whether the rounded arctangent is less than, equal to, or greater than
2950    /// the exact arctangent.
2951    ///
2952    /// This is `atan_with_period_rational` with a period of 2: see
2953    /// [`Float::atan_with_period_rational_prec_round_ref`] for the error bounds, the special cases,
2954    /// underflow, and the complexity, with $u = 2$. An input of $\pm1$ gives $\pm1/4$ and a zero
2955    /// input gives $0.0$, both exact at every precision; those are the only exact cases. Overflow
2956    /// is not possible, since $|\arctan(x)/\pi| < 1/2$.
2957    ///
2958    /// # Panics
2959    /// Panics if `prec` is zero, or if `rm` is `Exact` but the result cannot be represented exactly
2960    /// with the given precision.
2961    ///
2962    /// # Examples
2963    /// ```
2964    /// use malachite_base::rounding_modes::RoundingMode::*;
2965    /// use malachite_float::Float;
2966    /// use malachite_q::Rational;
2967    /// use std::cmp::Ordering::*;
2968    ///
2969    /// let (t, o) =
2970    ///     Float::atan_pi_rational_prec_round_ref(&Rational::from_unsigneds(1u8, 7), 10, Ceiling);
2971    /// assert_eq!(t.to_string(), "0.045227");
2972    /// assert_eq!(o, Greater);
2973    /// ```
2974    #[inline]
2975    pub fn atan_pi_rational_prec_round_ref(
2976        x: &Rational,
2977        prec: u64,
2978        rm: RoundingMode,
2979    ) -> (Self, Ordering) {
2980        Self::atan_with_period_rational_prec_round_ref(x, 2, prec, rm)
2981    }
2982
2983    /// Computes $\arctan(x)/\pi$, the arctangent of a [`Rational`] measured in half-turns, rounding
2984    /// the result to the nearest value of the specified precision and returning the result as a
2985    /// [`Float`]. The [`Rational`] is taken by value. An [`Ordering`] is also returned, indicating
2986    /// whether the rounded arctangent is less than, equal to, or greater than the exact arctangent.
2987    ///
2988    /// This is `atan_with_period_rational` with a period of 2: see
2989    /// [`Float::atan_with_period_rational_prec`] for the error bounds, the special cases,
2990    /// underflow, and the complexity, with $u = 2$. An input of $\pm1$ gives $\pm1/4$ and a zero
2991    /// input gives $0.0$, both exact at every precision; those are the only exact cases. Overflow
2992    /// is not possible, since $|\arctan(x)/\pi| < 1/2$.
2993    ///
2994    /// # Panics
2995    /// Panics if `prec` is zero.
2996    ///
2997    /// # Examples
2998    /// ```
2999    /// use malachite_float::Float;
3000    /// use malachite_q::Rational;
3001    /// use std::cmp::Ordering::*;
3002    ///
3003    /// let (t, o) = Float::atan_pi_rational_prec(Rational::from_unsigneds(1u8, 7), 53);
3004    /// assert_eq!(t.to_string(), "0.045167235300866547");
3005    /// assert_eq!(o, Less);
3006    /// ```
3007    #[inline]
3008    #[allow(clippy::needless_pass_by_value)]
3009    pub fn atan_pi_rational_prec(x: Rational, prec: u64) -> (Self, Ordering) {
3010        Self::atan_with_period_rational_prec_ref(&x, 2, prec)
3011    }
3012
3013    /// Computes $\arctan(x)/\pi$, the arctangent of a [`Rational`] measured in half-turns, rounding
3014    /// the result to the nearest value of the specified precision and returning the result as a
3015    /// [`Float`]. The [`Rational`] is taken by reference. An [`Ordering`] is also returned,
3016    /// indicating whether the rounded arctangent is less than, equal to, or greater than the exact
3017    /// arctangent.
3018    ///
3019    /// This is `atan_with_period_rational` with a period of 2: see
3020    /// [`Float::atan_with_period_rational_prec_ref`] for the error bounds, the special cases,
3021    /// underflow, and the complexity, with $u = 2$. An input of $\pm1$ gives $\pm1/4$ and a zero
3022    /// input gives $0.0$, both exact at every precision; those are the only exact cases. Overflow
3023    /// is not possible, since $|\arctan(x)/\pi| < 1/2$.
3024    ///
3025    /// # Panics
3026    /// Panics if `prec` is zero.
3027    ///
3028    /// # Examples
3029    /// ```
3030    /// use malachite_float::Float;
3031    /// use malachite_q::Rational;
3032    /// use std::cmp::Ordering::*;
3033    ///
3034    /// let (t, o) = Float::atan_pi_rational_prec_ref(&Rational::from_unsigneds(1u8, 7), 53);
3035    /// assert_eq!(t.to_string(), "0.045167235300866547");
3036    /// assert_eq!(o, Less);
3037    /// ```
3038    #[inline]
3039    pub fn atan_pi_rational_prec_ref(x: &Rational, prec: u64) -> (Self, Ordering) {
3040        Self::atan_with_period_rational_prec_ref(x, 2, prec)
3041    }
3042}
3043
3044impl Atan for Float {
3045    type Output = Self;
3046
3047    /// Computes $\arctan x$, the arctangent of a [`Float`], taking it by value.
3048    ///
3049    /// If the output has a precision, it is the precision of the input. If the arctangent is
3050    /// equidistant from two [`Float`]s with the specified precision, the [`Float`] with fewer 1s in
3051    /// its binary expansion is chosen. See [`RoundingMode`] for a description of the `Nearest`
3052    /// rounding mode.
3053    ///
3054    /// $$
3055    /// f(x) = \arctan x+\varepsilon.
3056    /// $$
3057    /// - If $x$ is NaN, $\varepsilon$ may be ignored or assumed to be 0.
3058    /// - If $x$ is not NaN, then $|\varepsilon| < 2^{\lfloor\log_2 |\arctan x|\rfloor-p}$, where
3059    ///   $p$ is the precision of the input.
3060    ///
3061    /// Special cases:
3062    /// - $f(\text{NaN})=\text{NaN}$
3063    /// - $f(\pm\infty)=\pm\pi/2$, rounded
3064    /// - $f(\pm0.0)=\pm0.0$
3065    ///
3066    /// See the [`Float::atan_round`] documentation for information on overflow and underflow.
3067    ///
3068    /// If you want to use a rounding mode other than `Nearest`, consider using
3069    /// [`Float::atan_round`] instead. If you want to specify the output precision, consider using
3070    /// [`Float::atan_prec`]. If you want both of these things, consider using
3071    /// [`Float::atan_prec_round`].
3072    ///
3073    /// # Worst-case complexity
3074    /// $T(n, e) = O(n (\log n)^3 \log\log n + (n+e) (\log (n+e))^2 \log\log (n+e))$
3075    ///
3076    /// $M(n, e) = O((n+e) \log (n+e))$
3077    ///
3078    /// where $T$ is time, $M$ is additional memory, $n$ is `self.significant_bits()`, and $e$ is
3079    /// the exponent of `self` (0 if `self` has no exponent or a negative one): the Taylor series at
3080    /// working precision $n$, summed by binary splitting for large $n$, costs the first term, and
3081    /// for $|x| \geq 4$ the argument is reduced modulo $2\pi$, which requires $\pi$ to about $n +
3082    /// e$ bits. Unlike most functions, `atan` therefore gets slower as the magnitude of its input
3083    /// grows, not just as the precision does.
3084    ///
3085    /// # Examples
3086    /// ```
3087    /// use malachite_base::num::arithmetic::traits::Atan;
3088    /// use malachite_base::num::basic::traits::*;
3089    /// use malachite_float::Float;
3090    ///
3091    /// assert!(Float::NAN.atan().is_nan());
3092    /// // an infinity has a precision of 1, so pi/2 rounds to 2
3093    /// assert_eq!(Float::INFINITY.atan().to_string(), "2.0");
3094    /// assert_eq!(Float::NEGATIVE_INFINITY.atan().to_string(), "-2.0");
3095    /// assert_eq!(Float::ZERO.atan().to_string(), "0.0");
3096    /// assert_eq!(Float::NEGATIVE_ZERO.atan().to_string(), "-0.0");
3097    /// assert_eq!(
3098    ///     Float::from_unsigned_prec(1u32, 100).0.atan().to_string(),
3099    ///     "0.78539816339744830961566084581983"
3100    /// );
3101    /// assert_eq!(
3102    ///     Float::from_unsigned_prec(100u32, 100).0.atan().to_string(),
3103    ///     "1.5607966601082313810249815754304"
3104    /// );
3105    /// ```
3106    #[inline]
3107    fn atan(self) -> Self {
3108        let prec = self.significant_bits();
3109        self.atan_prec_round(prec, Nearest).0
3110    }
3111}
3112
3113impl Atan for &Float {
3114    type Output = Float;
3115
3116    /// Computes $\arctan x$, the arctangent of a [`Float`], taking it by reference.
3117    ///
3118    /// If the output has a precision, it is the precision of the input. If the arctangent is
3119    /// equidistant from two [`Float`]s with the specified precision, the [`Float`] with fewer 1s in
3120    /// its binary expansion is chosen. See [`RoundingMode`] for a description of the `Nearest`
3121    /// rounding mode.
3122    ///
3123    /// $$
3124    /// f(x) = \arctan x+\varepsilon.
3125    /// $$
3126    /// - If $x$ is NaN, $\varepsilon$ may be ignored or assumed to be 0.
3127    /// - If $x$ is not NaN, then $|\varepsilon| < 2^{\lfloor\log_2 |\arctan x|\rfloor-p}$, where
3128    ///   $p$ is the precision of the input.
3129    ///
3130    /// Special cases:
3131    /// - $f(\text{NaN})=\text{NaN}$
3132    /// - $f(\pm\infty)=\pm\pi/2$, rounded
3133    /// - $f(\pm0.0)=\pm0.0$
3134    ///
3135    /// See the [`Float::atan_round`] documentation for information on overflow and underflow.
3136    ///
3137    /// If you want to use a rounding mode other than `Nearest`, consider using
3138    /// [`Float::atan_round_ref`] instead. If you want to specify the output precision, consider
3139    /// using [`Float::atan_prec_ref`]. If you want both of these things, consider using
3140    /// [`Float::atan_prec_round_ref`].
3141    ///
3142    /// # Worst-case complexity
3143    /// $T(n, e) = O(n (\log n)^3 \log\log n + (n+e) (\log (n+e))^2 \log\log (n+e))$
3144    ///
3145    /// $M(n, e) = O((n+e) \log (n+e))$
3146    ///
3147    /// where $T$ is time, $M$ is additional memory, $n$ is `self.significant_bits()`, and $e$ is
3148    /// the exponent of `self` (0 if `self` has no exponent or a negative one): the Taylor series at
3149    /// working precision $n$, summed by binary splitting for large $n$, costs the first term, and
3150    /// for $|x| \geq 4$ the argument is reduced modulo $2\pi$, which requires $\pi$ to about $n +
3151    /// e$ bits. Unlike most functions, `atan` therefore gets slower as the magnitude of its input
3152    /// grows, not just as the precision does.
3153    ///
3154    /// # Examples
3155    /// ```
3156    /// use malachite_base::num::arithmetic::traits::Atan;
3157    /// use malachite_base::num::basic::traits::*;
3158    /// use malachite_float::Float;
3159    ///
3160    /// assert!(Float::NAN.atan().is_nan());
3161    /// // an infinity has a precision of 1, so pi/2 rounds to 2
3162    /// assert_eq!(Float::INFINITY.atan().to_string(), "2.0");
3163    /// assert_eq!(Float::NEGATIVE_INFINITY.atan().to_string(), "-2.0");
3164    /// assert_eq!(Float::ZERO.atan().to_string(), "0.0");
3165    /// assert_eq!(Float::NEGATIVE_ZERO.atan().to_string(), "-0.0");
3166    /// assert_eq!(
3167    ///     (&Float::from_unsigned_prec(1u32, 100).0).atan().to_string(),
3168    ///     "0.78539816339744830961566084581983"
3169    /// );
3170    /// assert_eq!(
3171    ///     (&Float::from_unsigned_prec(100u32, 100).0)
3172    ///         .atan()
3173    ///         .to_string(),
3174    ///     "1.5607966601082313810249815754304"
3175    /// );
3176    /// ```
3177    #[inline]
3178    fn atan(self) -> Float {
3179        self.atan_prec_round_ref(self.significant_bits(), Nearest).0
3180    }
3181}
3182
3183impl AtanAssign for Float {
3184    /// Computes $\arctan x$, the arctangent of a [`Float`], in place.
3185    ///
3186    /// If the output has a precision, it is the precision of the input. If the arctangent is
3187    /// equidistant from two [`Float`]s with the specified precision, the [`Float`] with fewer 1s in
3188    /// its binary expansion is chosen. See [`RoundingMode`] for a description of the `Nearest`
3189    /// rounding mode.
3190    ///
3191    /// $$
3192    /// x \gets \arctan x+\varepsilon.
3193    /// $$
3194    /// - If $x$ is NaN, $\varepsilon$ may be ignored or assumed to be 0.
3195    /// - If $x$ is not NaN, then $|\varepsilon| < 2^{\lfloor\log_2 |\arctan x|\rfloor-p}$, where
3196    ///   $p$ is the precision of the input.
3197    ///
3198    /// See the [`Float::atan`] documentation for information on special cases, overflow, and
3199    /// underflow.
3200    ///
3201    /// If you want to use a rounding mode other than `Nearest`, consider using
3202    /// [`Float::atan_round_assign`] instead. If you want to specify the output precision, consider
3203    /// using [`Float::atan_prec_assign`]. If you want both of these things, consider using
3204    /// [`Float::atan_prec_round_assign`].
3205    ///
3206    /// # Worst-case complexity
3207    /// $T(n, e) = O(n (\log n)^3 \log\log n + (n+e) (\log (n+e))^2 \log\log (n+e))$
3208    ///
3209    /// $M(n, e) = O((n+e) \log (n+e))$
3210    ///
3211    /// where $T$ is time, $M$ is additional memory, $n$ is `self.significant_bits()`, and $e$ is
3212    /// the exponent of `self` (0 if `self` has no exponent or a negative one): the Taylor series at
3213    /// working precision $n$, summed by binary splitting for large $n$, costs the first term, and
3214    /// for $|x| \geq 4$ the argument is reduced modulo $2\pi$, which requires $\pi$ to about $n +
3215    /// e$ bits. Unlike most functions, `atan` therefore gets slower as the magnitude of its input
3216    /// grows, not just as the precision does.
3217    ///
3218    /// # Examples
3219    /// ```
3220    /// use malachite_base::num::arithmetic::traits::AtanAssign;
3221    /// use malachite_base::num::basic::traits::*;
3222    /// use malachite_float::Float;
3223    ///
3224    /// let mut x = Float::NAN;
3225    /// x.atan_assign();
3226    /// assert!(x.is_nan());
3227    ///
3228    /// let mut x = Float::INFINITY;
3229    /// x.atan_assign();
3230    /// assert_eq!(x.to_string(), "2.0");
3231    ///
3232    /// let mut x = Float::NEGATIVE_INFINITY;
3233    /// x.atan_assign();
3234    /// assert_eq!(x.to_string(), "-2.0");
3235    ///
3236    /// let mut x = Float::ZERO;
3237    /// x.atan_assign();
3238    /// assert_eq!(x.to_string(), "0.0");
3239    ///
3240    /// let mut x = Float::NEGATIVE_ZERO;
3241    /// x.atan_assign();
3242    /// assert_eq!(x.to_string(), "-0.0");
3243    ///
3244    /// let mut x = Float::from_unsigned_prec(1u32, 100).0;
3245    /// x.atan_assign();
3246    /// assert_eq!(x.to_string(), "0.78539816339744830961566084581983");
3247    ///
3248    /// let mut x = Float::from_unsigned_prec(100u32, 100).0;
3249    /// x.atan_assign();
3250    /// assert_eq!(x.to_string(), "1.5607966601082313810249815754304");
3251    /// ```
3252    #[inline]
3253    fn atan_assign(&mut self) {
3254        let prec = self.significant_bits();
3255        self.atan_prec_round_assign(prec, Nearest);
3256    }
3257}
3258
3259/// Computes $\arctan x$, the arctangent of a primitive float. Using this function is more accurate
3260/// than using the default `atan` function or the one provided by `libm`.
3261///
3262/// $$
3263/// f(x) = \arctan x+\varepsilon.
3264/// $$
3265/// - If $x$ is NaN, $\varepsilon$ may be ignored or assumed to be 0.
3266/// - If $x$ is not NaN, then $|\varepsilon| < 2^{\lfloor\log_2 |\arctan x|\rfloor-p}$, where $p$ is
3267///   the precision of the output (24 if `T` is a [`f32`] and 53 if `T` is a [`f64`]).
3268///
3269/// Special cases:
3270/// - $f(\text{NaN})=\text{NaN}$
3271/// - $f(\pm\infty)=\pm\pi/2$, rounded
3272/// - $f(\pm0.0)=\pm0.0$
3273///
3274/// Overflow is not possible, since the result lies in $(-\pi/2, \pi/2)$. The result is subnormal
3275/// only when $x$ is, and then it is $x$ itself, since $|\arctan x - x| < |x|^3/3$.
3276///
3277/// # Worst-case complexity
3278/// Constant time and additional memory.
3279///
3280/// # Examples
3281/// ```
3282/// use malachite_base::num::basic::traits::NegativeInfinity;
3283/// use malachite_base::num::float::NiceFloat;
3284/// use malachite_float::float::arithmetic::atan::primitive_float_atan;
3285///
3286/// assert!(primitive_float_atan(f32::NAN).is_nan());
3287/// assert_eq!(
3288///     NiceFloat(primitive_float_atan(f32::INFINITY)),
3289///     NiceFloat(core::f32::consts::FRAC_PI_2)
3290/// );
3291/// assert_eq!(
3292///     NiceFloat(primitive_float_atan(f32::NEGATIVE_INFINITY)),
3293///     NiceFloat(-core::f32::consts::FRAC_PI_2)
3294/// );
3295/// assert_eq!(NiceFloat(primitive_float_atan(0.0f32)), NiceFloat(0.0));
3296/// assert_eq!(NiceFloat(primitive_float_atan(-0.0f32)), NiceFloat(-0.0));
3297/// assert_eq!(
3298///     NiceFloat(primitive_float_atan(1.0f32)),
3299///     NiceFloat(core::f32::consts::FRAC_PI_4)
3300/// );
3301/// assert_eq!(
3302///     NiceFloat(primitive_float_atan(1.0f64)),
3303///     NiceFloat(core::f64::consts::FRAC_PI_4)
3304/// );
3305/// ```
3306#[inline]
3307#[allow(clippy::type_repetition_in_bounds)]
3308pub fn primitive_float_atan<T: PrimitiveFloat>(x: T) -> T
3309where
3310    Float: From<T> + PartialOrd<T>,
3311    for<'a> T: ExactFrom<&'a Float> + RoundingFrom<&'a Float>,
3312{
3313    emulate_float_to_float_fn(Float::atan_prec, x)
3314}
3315
3316/// Computes $\arctan x$, the arctangent of a [`Rational`], returning the result as a primitive
3317/// float.
3318///
3319/// $$
3320/// f(x) = \arctan x+\varepsilon,
3321/// $$
3322/// where $|\varepsilon| < 2^{\lfloor\log_2 |\arctan x|\rfloor-p}$, and $p$ is the precision of the
3323/// output (24 if `T` is a [`f32`] and 53 if `T` is a [`f64`]).
3324///
3325/// Special cases:
3326/// - $f(0)=0$
3327///
3328/// Overflow is not possible, since the result lies in $(-\pi/2, \pi/2)$. The result underflows, to
3329/// a subnormal or to zero, only when $x$ is tiny, since $|\arctan x| < |x|$ and $\arctan x$ is very
3330/// close to $x$ there.
3331///
3332/// # Worst-case complexity
3333/// $T(m) = O(m (\log m)^2 \log\log m)$
3334///
3335/// $M(m) = O(m \log m)$
3336///
3337/// where $T$ is time, $M$ is additional memory, and $m$ is `x.significant_bits()`.
3338///
3339/// # Examples
3340/// ```
3341/// use malachite_base::num::basic::traits::Zero;
3342/// use malachite_base::num::float::NiceFloat;
3343/// use malachite_float::float::arithmetic::atan::primitive_float_atan_rational;
3344/// use malachite_q::Rational;
3345///
3346/// assert_eq!(
3347///     NiceFloat(primitive_float_atan_rational::<f64>(&Rational::ZERO)),
3348///     NiceFloat(0.0)
3349/// );
3350/// assert_eq!(
3351///     NiceFloat(primitive_float_atan_rational::<f64>(
3352///         &Rational::from_unsigneds(1u8, 3)
3353///     )),
3354///     NiceFloat(0.3217505543966422)
3355/// );
3356/// assert_eq!(
3357///     NiceFloat(primitive_float_atan_rational::<f32>(
3358///         &Rational::from_unsigneds(1u8, 3)
3359///     )),
3360///     NiceFloat(0.32175055)
3361/// );
3362/// assert_eq!(
3363///     NiceFloat(primitive_float_atan_rational::<f64>(&Rational::from(10000))),
3364///     NiceFloat(1.5706963267952299)
3365/// );
3366/// ```
3367#[inline]
3368#[allow(clippy::type_repetition_in_bounds)]
3369pub fn primitive_float_atan_rational<T: PrimitiveFloat>(x: &Rational) -> T
3370where
3371    Float: PartialOrd<T>,
3372    for<'a> T: ExactFrom<&'a Float> + RoundingFrom<&'a Float>,
3373{
3374    emulate_rational_to_float_fn(Float::atan_rational_prec_ref, x)
3375}
3376
3377/// Computes $\arctan(x)u/(2\pi)$, the arctangent of a primitive float measured in $u$ths of a turn
3378/// (so that `u = 360` gives degrees).
3379///
3380/// $$
3381/// f(x,u) = \arctan(x)u/(2\pi)+\varepsilon.
3382/// $$
3383/// - If $x$ is NaN or zero, $u = 0$, or $|x|$ is 1 or infinite, $\varepsilon$ may be ignored or
3384///   assumed to be 0.
3385/// - Otherwise, $|\varepsilon| < 2^{\lfloor\log_2 |\arctan(x)u/(2\pi)|\rfloor-p}$, where $p$ is the
3386///   precision of the output (24 if `T` is a [`f32`] and 53 if `T` is a [`f64`]).
3387///
3388/// Special cases:
3389/// - $f(\text{NaN},u)=\text{NaN}$
3390/// - $f(\pm\infty,u)=\pm u/4$, a quarter turn
3391/// - $f(\pm0.0,u)=\pm0.0$
3392/// - $f(x,0)=\pm0.0$, with the sign of $x$, so that the function stays odd
3393/// - $f(\pm1,u)=\pm u/8$, an eighth of a turn
3394///
3395/// Overflow is not possible, since $|f(x,u)| < u/4 < 2^{62}$. The result is subnormal, or zero,
3396/// only when $x$ is tiny and $u$ is small, since the result is about $xu/(2\pi)$ there.
3397///
3398/// # Worst-case complexity
3399/// Constant time and additional memory.
3400///
3401/// # Examples
3402/// ```
3403/// use malachite_base::num::basic::traits::NegativeInfinity;
3404/// use malachite_base::num::float::NiceFloat;
3405/// use malachite_float::float::arithmetic::atan::primitive_float_atan_with_period;
3406///
3407/// assert!(primitive_float_atan_with_period(f32::NAN, 360).is_nan());
3408/// // an infinite input is a quarter turn
3409/// assert_eq!(
3410///     NiceFloat(primitive_float_atan_with_period(f32::INFINITY, 360)),
3411///     NiceFloat(90.0)
3412/// );
3413/// assert_eq!(
3414///     NiceFloat(primitive_float_atan_with_period(
3415///         f32::NEGATIVE_INFINITY,
3416///         360
3417///     )),
3418///     NiceFloat(-90.0)
3419/// );
3420/// // an input of 1 is an eighth of a turn
3421/// assert_eq!(
3422///     NiceFloat(primitive_float_atan_with_period(1.0f32, 360)),
3423///     NiceFloat(45.0)
3424/// );
3425/// assert_eq!(
3426///     NiceFloat(primitive_float_atan_with_period(2.0f32, 360)),
3427///     NiceFloat(63.434948)
3428/// );
3429/// assert_eq!(
3430///     NiceFloat(primitive_float_atan_with_period(2.0f64, 360)),
3431///     NiceFloat(63.43494882292201)
3432/// );
3433/// ```
3434#[inline]
3435#[allow(clippy::type_repetition_in_bounds)]
3436pub fn primitive_float_atan_with_period<T: PrimitiveFloat>(x: T, u: u64) -> T
3437where
3438    Float: From<T> + PartialOrd<T>,
3439    for<'a> T: ExactFrom<&'a Float> + RoundingFrom<&'a Float>,
3440{
3441    emulate_float_to_float_fn(|x, prec| Float::atan_with_period_prec(x, u, prec), x)
3442}
3443
3444/// Computes $\arctan(x)u/(2\pi)$, the arctangent of a [`Rational`] measured in $u$ths of a turn (so
3445/// that `u = 360` gives degrees), returning the result as a primitive float.
3446///
3447/// $$
3448/// f(x,u) = \arctan(x)u/(2\pi)+\varepsilon.
3449/// $$
3450/// - If $x$ is zero, $u = 0$, or $|x|$ is 1, $\varepsilon$ may be ignored or assumed to be 0.
3451/// - Otherwise, $|\varepsilon| < 2^{\lfloor\log_2 |\arctan(x)u/(2\pi)|\rfloor-p}$, where $p$ is the
3452///   precision of the output (24 if `T` is a [`f32`] and 53 if `T` is a [`f64`]).
3453///
3454/// Special cases:
3455/// - $f(0,u)=0.0$
3456/// - $f(x,0)=\pm0.0$, with the sign of $x$, so that the function stays odd
3457/// - $f(\pm1,u)=\pm u/8$, an eighth of a turn
3458///
3459/// Overflow is not possible, since $|f(x,u)| < u/4 < 2^{62}$. The result is subnormal, or zero,
3460/// only when $x$ is tiny and $u$ is small, since the result is about $xu/(2\pi)$ there.
3461///
3462/// # Worst-case complexity
3463/// $T(m) = O(m \log m \log\log m)$
3464///
3465/// $M(m) = O(m \log m)$
3466///
3467/// where $T$ is time, $M$ is additional memory, and $m$ is `x.significant_bits()`.
3468///
3469/// # Examples
3470/// ```
3471/// use malachite_base::num::basic::traits::{One, Zero};
3472/// use malachite_base::num::float::NiceFloat;
3473/// use malachite_float::float::arithmetic::atan::primitive_float_atan_with_period_rational;
3474/// use malachite_q::Rational;
3475///
3476/// assert_eq!(
3477///     NiceFloat(primitive_float_atan_with_period_rational::<f64>(
3478///         &Rational::ZERO,
3479///         360
3480///     )),
3481///     NiceFloat(0.0)
3482/// );
3483/// // an input of 1 is an eighth of a turn
3484/// assert_eq!(
3485///     NiceFloat(primitive_float_atan_with_period_rational::<f64>(
3486///         &Rational::ONE,
3487///         360
3488///     )),
3489///     NiceFloat(45.0)
3490/// );
3491/// assert_eq!(
3492///     NiceFloat(primitive_float_atan_with_period_rational::<f64>(
3493///         &Rational::from_unsigneds(1u8, 3),
3494///         360
3495///     )),
3496///     NiceFloat(18.43494882292201)
3497/// );
3498/// assert_eq!(
3499///     NiceFloat(primitive_float_atan_with_period_rational::<f32>(
3500///         &Rational::from_unsigneds(1u8, 3),
3501///         360
3502///     )),
3503///     NiceFloat(18.434948)
3504/// );
3505/// ```
3506#[inline]
3507#[allow(clippy::type_repetition_in_bounds)]
3508pub fn primitive_float_atan_with_period_rational<T: PrimitiveFloat>(x: &Rational, u: u64) -> T
3509where
3510    Float: PartialOrd<T>,
3511    for<'a> T: ExactFrom<&'a Float> + RoundingFrom<&'a Float>,
3512{
3513    emulate_rational_to_float_fn(
3514        |x, prec| Float::atan_with_period_rational_prec_ref(x, u, prec),
3515        x,
3516    )
3517}
3518
3519/// Computes $\arctan(x)/\pi$, the arctangent of a primitive float measured in half-turns.
3520///
3521/// This is `primitive_float_atan_with_period` with a period of 2: see
3522/// [`primitive_float_atan_with_period`] for the error bound and the special cases, with $u = 2$. An
3523/// infinite input gives exactly $\pm1/2$, an input of $\pm1$ exactly $\pm1/4$, and a zero input
3524/// exactly $\pm0.0$; those are the only exact cases. Overflow is not possible, since
3525/// $|\arctan(x)/\pi| < 1/2$, and the result is subnormal, or zero, only for a subnormal input.
3526///
3527/// # Worst-case complexity
3528/// Constant time and additional memory.
3529///
3530/// # Examples
3531/// ```
3532/// use malachite_base::num::basic::traits::NegativeInfinity;
3533/// use malachite_base::num::float::NiceFloat;
3534/// use malachite_float::float::arithmetic::atan::primitive_float_atan_pi;
3535///
3536/// assert!(primitive_float_atan_pi(f32::NAN).is_nan());
3537/// // an infinite input is half a turn
3538/// assert_eq!(
3539///     NiceFloat(primitive_float_atan_pi(f32::INFINITY)),
3540///     NiceFloat(0.5)
3541/// );
3542/// assert_eq!(
3543///     NiceFloat(primitive_float_atan_pi(f32::NEGATIVE_INFINITY)),
3544///     NiceFloat(-0.5)
3545/// );
3546/// // an input of 1 is a quarter of a half-turn
3547/// assert_eq!(NiceFloat(primitive_float_atan_pi(1.0f32)), NiceFloat(0.25));
3548/// assert_eq!(
3549///     NiceFloat(primitive_float_atan_pi(0.1f32)),
3550///     NiceFloat(0.03172552)
3551/// );
3552/// assert_eq!(
3553///     NiceFloat(primitive_float_atan_pi(0.1f64)),
3554///     NiceFloat(0.031725517430553574)
3555/// );
3556/// ```
3557#[inline]
3558#[allow(clippy::type_repetition_in_bounds)]
3559pub fn primitive_float_atan_pi<T: PrimitiveFloat>(x: T) -> T
3560where
3561    Float: From<T> + PartialOrd<T>,
3562    for<'a> T: ExactFrom<&'a Float> + RoundingFrom<&'a Float>,
3563{
3564    primitive_float_atan_with_period(x, 2)
3565}
3566
3567/// Computes $\arctan(x)/\pi$, the arctangent of a [`Rational`] measured in half-turns, returning
3568/// the result as a primitive float.
3569///
3570/// This is `primitive_float_atan_with_period_rational` with a period of 2: see
3571/// [`primitive_float_atan_with_period_rational`] for the error bound and the special cases, with $u
3572/// = 2$. An input of $\pm1$ gives exactly $\pm1/4$ and a zero input exactly $0.0$; those are the
3573/// only exact cases. Overflow is not possible, since $|\arctan(x)/\pi| < 1/2$.
3574///
3575/// # Worst-case complexity
3576/// $T(m) = O(m \log m \log\log m)$
3577///
3578/// $M(m) = O(m \log m)$
3579///
3580/// where $T$ is time, $M$ is additional memory, and $m$ is `x.significant_bits()`.
3581///
3582/// # Examples
3583/// ```
3584/// use malachite_base::num::basic::traits::{One, Zero};
3585/// use malachite_base::num::float::NiceFloat;
3586/// use malachite_float::float::arithmetic::atan::primitive_float_atan_pi_rational;
3587/// use malachite_q::Rational;
3588///
3589/// assert_eq!(
3590///     NiceFloat(primitive_float_atan_pi_rational::<f64>(&Rational::ZERO)),
3591///     NiceFloat(0.0)
3592/// );
3593/// // an input of 1 is a quarter of a half-turn
3594/// assert_eq!(
3595///     NiceFloat(primitive_float_atan_pi_rational::<f64>(&Rational::ONE)),
3596///     NiceFloat(0.25)
3597/// );
3598/// assert_eq!(
3599///     NiceFloat(primitive_float_atan_pi_rational::<f64>(
3600///         &Rational::from_unsigneds(1u8, 3)
3601///     )),
3602///     NiceFloat(0.10241638234956672)
3603/// );
3604/// assert_eq!(
3605///     NiceFloat(primitive_float_atan_pi_rational::<f32>(
3606///         &Rational::from_unsigneds(1u8, 3)
3607///     )),
3608///     NiceFloat(0.10241638)
3609/// );
3610/// ```
3611#[inline]
3612#[allow(clippy::type_repetition_in_bounds)]
3613pub fn primitive_float_atan_pi_rational<T: PrimitiveFloat>(x: &Rational) -> T
3614where
3615    Float: PartialOrd<T>,
3616    for<'a> T: ExactFrom<&'a Float> + RoundingFrom<&'a Float>,
3617{
3618    primitive_float_atan_with_period_rational(x, 2)
3619}