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