xref: /llvm-project/libc/src/math/generic/atan2f.cpp (revision a7da702377ef857a6b2dccf5f07f77b489be1dd1)
1 //===-- Single-precision atan2f function ----------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "src/math/atan2f.h"
10 #include "inv_trigf_utils.h"
11 #include "src/__support/FPUtil/FPBits.h"
12 #include "src/__support/FPUtil/PolyEval.h"
13 #include "src/__support/FPUtil/double_double.h"
14 #include "src/__support/FPUtil/multiply_add.h"
15 #include "src/__support/FPUtil/nearest_integer.h"
16 #include "src/__support/FPUtil/rounding_mode.h"
17 #include "src/__support/macros/config.h"
18 #include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
19 
20 namespace LIBC_NAMESPACE_DECL {
21 
22 namespace {
23 
24 #ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
25 
26 // Look up tables for accurate pass:
27 
28 // atan(i/16) with i = 0..16, generated by Sollya with:
29 // > for i from 0 to 16 do {
30 //     a = round(atan(i/16), D, RN);
31 //     b = round(atan(i/16) - a, D, RN);
32 //     print("{", b, ",", a, "},");
33 //   };
34 constexpr fputil::DoubleDouble ATAN_I[17] = {
35     {0.0, 0.0},
36     {-0x1.c934d86d23f1dp-60, 0x1.ff55bb72cfdeap-5},
37     {-0x1.cd37686760c17p-59, 0x1.fd5ba9aac2f6ep-4},
38     {0x1.347b0b4f881cap-58, 0x1.7b97b4bce5b02p-3},
39     {0x1.8ab6e3cf7afbdp-57, 0x1.f5b75f92c80ddp-3},
40     {-0x1.963a544b672d8p-57, 0x1.362773707ebccp-2},
41     {-0x1.c63aae6f6e918p-56, 0x1.6f61941e4def1p-2},
42     {-0x1.24dec1b50b7ffp-56, 0x1.a64eec3cc23fdp-2},
43     {0x1.a2b7f222f65e2p-56, 0x1.dac670561bb4fp-2},
44     {-0x1.d5b495f6349e6p-56, 0x1.0657e94db30dp-1},
45     {-0x1.928df287a668fp-58, 0x1.1e00babdefeb4p-1},
46     {0x1.1021137c71102p-55, 0x1.345f01cce37bbp-1},
47     {0x1.2419a87f2a458p-56, 0x1.4978fa3269ee1p-1},
48     {0x1.0028e4bc5e7cap-57, 0x1.5d58987169b18p-1},
49     {-0x1.8c34d25aadef6p-56, 0x1.700a7c5784634p-1},
50     {-0x1.bf76229d3b917p-56, 0x1.819d0b7158a4dp-1},
51     {0x1.1a62633145c07p-55, 0x1.921fb54442d18p-1},
52 };
53 
54 // Taylor polynomial, generated by Sollya with:
55 // > for i from 0 to 8 do {
56 //     j = (-1)^(i + 1)/(2*i + 1);
57 //     a = round(j, D, RN);
58 //     b = round(j - a, D, RN);
59 //     print("{", b, ",", a, "},");
60 //   };
61 constexpr fputil::DoubleDouble COEFFS[9] = {
62     {0.0, 1.0},                                      // 1
63     {-0x1.5555555555555p-56, -0x1.5555555555555p-2}, // -1/3
64     {-0x1.999999999999ap-57, 0x1.999999999999ap-3},  // 1/5
65     {-0x1.2492492492492p-57, -0x1.2492492492492p-3}, // -1/7
66     {0x1.c71c71c71c71cp-58, 0x1.c71c71c71c71cp-4},   // 1/9
67     {0x1.745d1745d1746p-59, -0x1.745d1745d1746p-4},  // -1/11
68     {-0x1.3b13b13b13b14p-58, 0x1.3b13b13b13b14p-4},  // 1/13
69     {-0x1.1111111111111p-60, -0x1.1111111111111p-4}, // -1/15
70     {0x1.e1e1e1e1e1e1ep-61, 0x1.e1e1e1e1e1e1ep-5},   // 1/17
71 };
72 
73 // Veltkamp's splitting of a double precision into hi + lo, where the hi part is
74 // slightly smaller than an even split, so that the product of
75 //   hi * (s1 * k + s2) is exact,
76 // where:
77 //   s1, s2 are single precsion,
78 //   1/16 <= s1/s2 <= 1
79 //   1/16 <= k <= 1 is an integer.
80 // So the maximal precision of (s1 * k + s2) is:
81 //   prec(s1 * k + s2) = 2 + log2(msb(s2)) - log2(lsb(k_d * s1))
82 //                     = 2 + log2(msb(s1)) + 4 - log2(lsb(k_d)) - log2(lsb(s1))
83 //                     = 2 + log2(lsb(s1)) + 23 + 4 - (-4) - log2(lsb(s1))
84 //                     = 33.
85 // Thus, the Veltkamp splitting constant is C = 2^33 + 1.
86 // This is used when FMA instruction is not available.
87 [[maybe_unused]] constexpr fputil::DoubleDouble split_d(double a) {
88   fputil::DoubleDouble r{0.0, 0.0};
89   constexpr double C = 0x1.0p33 + 1.0;
90   double t1 = C * a;
91   double t2 = a - t1;
92   r.hi = t1 + t2;
93   r.lo = a - r.hi;
94   return r;
95 }
96 
97 // Compute atan( num_d / den_d ) in double-double precision.
98 //   num_d      = min(|x|, |y|)
99 //   den_d      = max(|x|, |y|)
100 //   q_d        = num_d / den_d
101 //   idx, k_d   = round( 2^4 * num_d / den_d )
102 //   final_sign = sign of the final result
103 //   const_term = the constant term in the final expression.
104 float atan2f_double_double(double num_d, double den_d, double q_d, int idx,
105                            double k_d, double final_sign,
106                            const fputil::DoubleDouble &const_term) {
107   fputil::DoubleDouble q;
108   double num_r, den_r;
109 
110   if (idx != 0) {
111     // The following range reduction is accurate even without fma for
112     //   1/16 <= n/d <= 1.
113     // atan(n/d) - atan(idx/16) = atan((n/d - idx/16) / (1 + (n/d) * (idx/16)))
114     //                          = atan((n - d*(idx/16)) / (d + n*idx/16))
115     k_d *= 0x1.0p-4;
116     num_r = fputil::multiply_add(k_d, -den_d, num_d); // Exact
117     den_r = fputil::multiply_add(k_d, num_d, den_d);  // Exact
118     q.hi = num_r / den_r;
119   } else {
120     // For 0 < n/d < 1/16, we just need to calculate the lower part of their
121     // quotient.
122     q.hi = q_d;
123     num_r = num_d;
124     den_r = den_d;
125   }
126 #ifdef LIBC_TARGET_CPU_HAS_FMA
127   q.lo = fputil::multiply_add(q.hi, -den_r, num_r) / den_r;
128 #else
129   // Compute `(num_r - q.hi * den_r) / den_r` accurately without FMA
130   // instructions.
131   fputil::DoubleDouble q_hi_dd = split_d(q.hi);
132   double t1 = fputil::multiply_add(q_hi_dd.hi, -den_r, num_r); // Exact
133   double t2 = fputil::multiply_add(q_hi_dd.lo, -den_r, t1);
134   q.lo = t2 / den_r;
135 #endif // LIBC_TARGET_CPU_HAS_FMA
136 
137   // Taylor polynomial, evaluating using Horner's scheme:
138   //   P = x - x^3/3 + x^5/5 -x^7/7 + x^9/9 - x^11/11 + x^13/13 - x^15/15
139   //       + x^17/17
140   //     = x*(1 + x^2*(-1/3 + x^2*(1/5 + x^2*(-1/7 + x^2*(1/9 + x^2*
141   //          *(-1/11 + x^2*(1/13 + x^2*(-1/15 + x^2 * 1/17))))))))
142   fputil::DoubleDouble q2 = fputil::quick_mult(q, q);
143   fputil::DoubleDouble p_dd =
144       fputil::polyeval(q2, COEFFS[0], COEFFS[1], COEFFS[2], COEFFS[3],
145                        COEFFS[4], COEFFS[5], COEFFS[6], COEFFS[7], COEFFS[8]);
146   fputil::DoubleDouble r_dd =
147       fputil::add(const_term, fputil::multiply_add(q, p_dd, ATAN_I[idx]));
148   r_dd.hi *= final_sign;
149   r_dd.lo *= final_sign;
150 
151   // Make sure the sum is normalized:
152   fputil::DoubleDouble rr = fputil::exact_add(r_dd.hi, r_dd.lo);
153   // Round to odd.
154   uint64_t rr_bits = cpp::bit_cast<uint64_t>(rr.hi);
155   if (LIBC_UNLIKELY(((rr_bits & 0xfff'ffff) == 0) && (rr.lo != 0.0))) {
156     Sign hi_sign = fputil::FPBits<double>(rr.hi).sign();
157     Sign lo_sign = fputil::FPBits<double>(rr.lo).sign();
158     if (hi_sign == lo_sign) {
159       ++rr_bits;
160     } else if ((rr_bits & fputil::FPBits<double>::FRACTION_MASK) > 0) {
161       --rr_bits;
162     }
163   }
164 
165   return static_cast<float>(cpp::bit_cast<double>(rr_bits));
166 }
167 
168 #endif // !LIBC_MATH_HAS_SKIP_ACCURATE_PASS
169 
170 } // anonymous namespace
171 
172 // There are several range reduction steps we can take for atan2(y, x) as
173 // follow:
174 
175 // * Range reduction 1: signness
176 // atan2(y, x) will return a number between -PI and PI representing the angle
177 // forming by the 0x axis and the vector (x, y) on the 0xy-plane.
178 // In particular, we have that:
179 //   atan2(y, x) = atan( y/x )         if x >= 0 and y >= 0 (I-quadrant)
180 //               = pi + atan( y/x )    if x < 0 and y >= 0  (II-quadrant)
181 //               = -pi + atan( y/x )   if x < 0 and y < 0   (III-quadrant)
182 //               = atan( y/x )         if x >= 0 and y < 0  (IV-quadrant)
183 // Since atan function is odd, we can use the formula:
184 //   atan(-u) = -atan(u)
185 // to adjust the above conditions a bit further:
186 //   atan2(y, x) = atan( |y|/|x| )         if x >= 0 and y >= 0 (I-quadrant)
187 //               = pi - atan( |y|/|x| )    if x < 0 and y >= 0  (II-quadrant)
188 //               = -pi + atan( |y|/|x| )   if x < 0 and y < 0   (III-quadrant)
189 //               = -atan( |y|/|x| )        if x >= 0 and y < 0  (IV-quadrant)
190 // Which can be simplified to:
191 //   atan2(y, x) = sign(y) * atan( |y|/|x| )             if x >= 0
192 //               = sign(y) * (pi - atan( |y|/|x| ))      if x < 0
193 
194 // * Range reduction 2: reciprocal
195 // Now that the argument inside atan is positive, we can use the formula:
196 //   atan(1/x) = pi/2 - atan(x)
197 // to make the argument inside atan <= 1 as follow:
198 //   atan2(y, x) = sign(y) * atan( |y|/|x|)            if 0 <= |y| <= x
199 //               = sign(y) * (pi/2 - atan( |x|/|y| )   if 0 <= x < |y|
200 //               = sign(y) * (pi - atan( |y|/|x| ))    if 0 <= |y| <= -x
201 //               = sign(y) * (pi/2 + atan( |x|/|y| ))  if 0 <= -x < |y|
202 
203 // * Range reduction 3: look up table.
204 // After the previous two range reduction steps, we reduce the problem to
205 // compute atan(u) with 0 <= u <= 1, or to be precise:
206 //   atan( n / d ) where n = min(|x|, |y|) and d = max(|x|, |y|).
207 // An accurate polynomial approximation for the whole [0, 1] input range will
208 // require a very large degree.  To make it more efficient, we reduce the input
209 // range further by finding an integer idx such that:
210 //   | n/d - idx/16 | <= 1/32.
211 // In particular,
212 //   idx := 2^-4 * round(2^4 * n/d)
213 // Then for the fast pass, we find a polynomial approximation for:
214 //   atan( n/d ) ~ atan( idx/16 ) + (n/d - idx/16) * Q(n/d - idx/16)
215 // For the accurate pass, we use the addition formula:
216 //   atan( n/d ) - atan( idx/16 ) = atan( (n/d - idx/16)/(1 + (n*idx)/(16*d)) )
217 //                                = atan( (n - d * idx/16)/(d + n * idx/16) )
218 // And finally we use Taylor polynomial to compute the RHS in the accurate pass:
219 //   atan(u) ~ P(u) = u - u^3/3 + u^5/5 - u^7/7 + u^9/9 - u^11/11 + u^13/13 -
220 //                      - u^15/15 + u^17/17
221 // It's error in double-double precision is estimated in Sollya to be:
222 // > P = x - x^3/3 + x^5/5 -x^7/7 + x^9/9 - x^11/11 + x^13/13 - x^15/15
223 //       + x^17/17;
224 // > dirtyinfnorm(atan(x) - P, [-2^-5, 2^-5]);
225 // 0x1.aec6f...p-100
226 // which is about rounding errors of double-double (2^-104).
227 
228 LLVM_LIBC_FUNCTION(float, atan2f, (float y, float x)) {
229   using FPBits = typename fputil::FPBits<float>;
230   constexpr double IS_NEG[2] = {1.0, -1.0};
231   constexpr double PI = 0x1.921fb54442d18p1;
232   constexpr double PI_LO = 0x1.1a62633145c07p-53;
233   constexpr double PI_OVER_4 = 0x1.921fb54442d18p-1;
234   constexpr double PI_OVER_2 = 0x1.921fb54442d18p0;
235   constexpr double THREE_PI_OVER_4 = 0x1.2d97c7f3321d2p+1;
236   // Adjustment for constant term:
237   //   CONST_ADJ[x_sign][y_sign][recip]
238   constexpr fputil::DoubleDouble CONST_ADJ[2][2][2] = {
239       {{{0.0, 0.0}, {-PI_LO / 2, -PI_OVER_2}},
240        {{-0.0, -0.0}, {-PI_LO / 2, -PI_OVER_2}}},
241       {{{-PI_LO, -PI}, {PI_LO / 2, PI_OVER_2}},
242        {{-PI_LO, -PI}, {PI_LO / 2, PI_OVER_2}}}};
243 
244   FPBits x_bits(x), y_bits(y);
245   bool x_sign = x_bits.sign().is_neg();
246   bool y_sign = y_bits.sign().is_neg();
247   x_bits.set_sign(Sign::POS);
248   y_bits.set_sign(Sign::POS);
249   uint32_t x_abs = x_bits.uintval();
250   uint32_t y_abs = y_bits.uintval();
251   uint32_t max_abs = x_abs > y_abs ? x_abs : y_abs;
252   uint32_t min_abs = x_abs <= y_abs ? x_abs : y_abs;
253   float num_f = FPBits(min_abs).get_val();
254   float den_f = FPBits(max_abs).get_val();
255   double num_d = static_cast<double>(num_f);
256   double den_d = static_cast<double>(den_f);
257 
258   if (LIBC_UNLIKELY(max_abs >= 0x7f80'0000U || num_d == 0.0)) {
259     if (x_bits.is_nan() || y_bits.is_nan())
260       return FPBits::quiet_nan().get_val();
261     double x_d = static_cast<double>(x);
262     double y_d = static_cast<double>(y);
263     size_t x_except = (x_d == 0.0) ? 0 : (x_abs == 0x7f80'0000 ? 2 : 1);
264     size_t y_except = (y_d == 0.0) ? 0 : (y_abs == 0x7f80'0000 ? 2 : 1);
265 
266     // Exceptional cases:
267     //   EXCEPT[y_except][x_except][x_is_neg]
268     // with x_except & y_except:
269     //   0: zero
270     //   1: finite, non-zero
271     //   2: infinity
272     constexpr double EXCEPTS[3][3][2] = {
273         {{0.0, PI}, {0.0, PI}, {0.0, PI}},
274         {{PI_OVER_2, PI_OVER_2}, {0.0, 0.0}, {0.0, PI}},
275         {{PI_OVER_2, PI_OVER_2},
276          {PI_OVER_2, PI_OVER_2},
277          {PI_OVER_4, THREE_PI_OVER_4}},
278     };
279 
280     double r = IS_NEG[y_sign] * EXCEPTS[y_except][x_except][x_sign];
281 
282     return static_cast<float>(r);
283   }
284 
285   bool recip = x_abs < y_abs;
286   double final_sign = IS_NEG[(x_sign != y_sign) != recip];
287   fputil::DoubleDouble const_term = CONST_ADJ[x_sign][y_sign][recip];
288   double q_d = num_d / den_d;
289 
290   double k_d = fputil::nearest_integer(q_d * 0x1.0p4);
291   int idx = static_cast<int>(k_d);
292   double r;
293 
294 #ifdef LIBC_MATH_HAS_SMALL_TABLES
295   double p = atan_eval_no_table(num_d, den_d, k_d * 0x1.0p-4);
296   r = final_sign * (p + (const_term.hi + ATAN_K_OVER_16[idx]));
297 #else
298   q_d = fputil::multiply_add(k_d, -0x1.0p-4, q_d);
299 
300   double p = atan_eval(q_d, idx);
301   r = final_sign *
302       fputil::multiply_add(q_d, p, const_term.hi + ATAN_COEFFS[idx][0]);
303 #endif // LIBC_MATH_HAS_SMALL_TABLES
304 
305 #ifdef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
306   return static_cast<float>(r);
307 #else
308   constexpr uint32_t LOWER_ERR = 4;
309   // Mask sticky bits in double precision before rounding to single precision.
310   constexpr uint32_t MASK =
311       mask_trailing_ones<uint32_t, fputil::FPBits<double>::SIG_LEN -
312                                        FPBits::SIG_LEN - 1>();
313   constexpr uint32_t UPPER_ERR = MASK - LOWER_ERR;
314 
315   uint32_t r_bits = static_cast<uint32_t>(cpp::bit_cast<uint64_t>(r)) & MASK;
316 
317   // Ziv's rounding test.
318   if (LIBC_LIKELY(r_bits > LOWER_ERR && r_bits < UPPER_ERR))
319     return static_cast<float>(r);
320 
321   return atan2f_double_double(num_d, den_d, q_d, idx, k_d, final_sign,
322                               const_term);
323 #endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
324 }
325 
326 } // namespace LIBC_NAMESPACE_DECL
327