1//===-- Implementation header for atan2 -------------------------*- C++ -*-===//
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#ifndef LLVM_LIBC_SRC___SUPPORT_MATH_ATAN2_H
10#define LLVM_LIBC_SRC___SUPPORT_MATH_ATAN2_H
11
12#include "atan_utils.h"
13#include "src/__support/FPUtil/FEnvImpl.h"
14#include "src/__support/FPUtil/FPBits.h"
15#include "src/__support/FPUtil/double_double.h"
16#include "src/__support/FPUtil/multiply_add.h"
17#include "src/__support/FPUtil/nearest_integer.h"
18#include "src/__support/macros/config.h"
19#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
20
21namespace LIBC_NAMESPACE_DECL {
22
23namespace math {
24
25// There are several range reduction steps we can take for atan2(y, x) as
26// follow:
27
28// * Range reduction 1: signness
29// atan2(y, x) will return a number between -PI and PI representing the angle
30// forming by the 0x axis and the vector (x, y) on the 0xy-plane.
31// In particular, we have that:
32// atan2(y, x) = atan( y/x ) if x >= 0 and y >= 0 (I-quadrant)
33// = pi + atan( y/x ) if x < 0 and y >= 0 (II-quadrant)
34// = -pi + atan( y/x ) if x < 0 and y < 0 (III-quadrant)
35// = atan( y/x ) if x >= 0 and y < 0 (IV-quadrant)
36// Since atan function is odd, we can use the formula:
37// atan(-u) = -atan(u)
38// to adjust the above conditions a bit further:
39// atan2(y, x) = atan( |y|/|x| ) if x >= 0 and y >= 0 (I-quadrant)
40// = pi - atan( |y|/|x| ) if x < 0 and y >= 0 (II-quadrant)
41// = -pi + atan( |y|/|x| ) if x < 0 and y < 0 (III-quadrant)
42// = -atan( |y|/|x| ) if x >= 0 and y < 0 (IV-quadrant)
43// Which can be simplified to:
44// atan2(y, x) = sign(y) * atan( |y|/|x| ) if x >= 0
45// = sign(y) * (pi - atan( |y|/|x| )) if x < 0
46
47// * Range reduction 2: reciprocal
48// Now that the argument inside atan is positive, we can use the formula:
49// atan(1/x) = pi/2 - atan(x)
50// to make the argument inside atan <= 1 as follow:
51// atan2(y, x) = sign(y) * atan( |y|/|x|) if 0 <= |y| <= x
52// = sign(y) * (pi/2 - atan( |x|/|y| ) if 0 <= x < |y|
53// = sign(y) * (pi - atan( |y|/|x| )) if 0 <= |y| <= -x
54// = sign(y) * (pi/2 + atan( |x|/|y| )) if 0 <= -x < |y|
55
56// * Range reduction 3: look up table.
57// After the previous two range reduction steps, we reduce the problem to
58// compute atan(u) with 0 <= u <= 1, or to be precise:
59// atan( n / d ) where n = min(|x|, |y|) and d = max(|x|, |y|).
60// An accurate polynomial approximation for the whole [0, 1] input range will
61// require a very large degree. To make it more efficient, we reduce the input
62// range further by finding an integer idx such that:
63// | n/d - idx/64 | <= 1/128.
64// In particular,
65// idx := round(2^6 * n/d)
66// Then for the fast pass, we find a polynomial approximation for:
67// atan( n/d ) ~ atan( idx/64 ) + (n/d - idx/64) * Q(n/d - idx/64)
68// For the accurate pass, we use the addition formula:
69// atan( n/d ) - atan( idx/64 ) = atan( (n/d - idx/64)/(1 + (n*idx)/(64*d)) )
70// = atan( (n - d*(idx/64))/(d + n*(idx/64)) )
71// And for the fast pass, we use degree-9 Taylor polynomial to compute the RHS:
72// atan(u) ~ P(u) = u - u^3/3 + u^5/5 - u^7/7 + u^9/9
73// with absolute errors bounded by:
74// |atan(u) - P(u)| < |u|^11 / 11 < 2^-80
75// and relative errors bounded by:
76// |(atan(u) - P(u)) / P(u)| < u^10 / 11 < 2^-73.
77
78namespace atan2_internal {
79
80using DoubleDouble = fputil::DoubleDouble;
81
82LIBC_INLINE_VAR constexpr DoubleDouble ZERO = {.lo: 0.0, .hi: 0.0};
83LIBC_INLINE_VAR constexpr DoubleDouble MZERO = {.lo: -0.0, .hi: -0.0};
84LIBC_INLINE_VAR constexpr DoubleDouble PI = {.lo: 0x1.1a62633145c07p-53,
85 .hi: 0x1.921fb54442d18p+1};
86LIBC_INLINE_VAR constexpr DoubleDouble MPI = {.lo: -0x1.1a62633145c07p-53,
87 .hi: -0x1.921fb54442d18p+1};
88LIBC_INLINE_VAR constexpr DoubleDouble PI_OVER_2 = {.lo: 0x1.1a62633145c07p-54,
89 .hi: 0x1.921fb54442d18p0};
90LIBC_INLINE_VAR constexpr DoubleDouble MPI_OVER_2 = {.lo: -0x1.1a62633145c07p-54,
91 .hi: -0x1.921fb54442d18p0};
92LIBC_INLINE_VAR constexpr DoubleDouble PI_OVER_4 = {.lo: 0x1.1a62633145c07p-55,
93 .hi: 0x1.921fb54442d18p-1};
94LIBC_INLINE_VAR constexpr DoubleDouble THREE_PI_OVER_4 = {.lo: 0x1.a79394c9e8a0ap-54,
95 .hi: 0x1.2d97c7f3321d2p+1};
96
97// Adjustment for constant term:
98// CONST_ADJ[x_sign][y_sign][recip]
99LIBC_INLINE_VAR constexpr DoubleDouble CONST_ADJ[2][2][2] = {
100 {{ZERO, MPI_OVER_2}, {MZERO, MPI_OVER_2}},
101 {{MPI, PI_OVER_2}, {MPI, PI_OVER_2}}};
102
103// Exceptional cases:
104// EXCEPT[y_except][x_except][x_is_neg]
105// with x_except & y_except:
106// 0: zero
107// 1: finite, non-zero
108// 2: infinity
109LIBC_INLINE_VAR constexpr DoubleDouble EXCEPTS[3][3][2] = {
110 {{ZERO, PI}, {ZERO, PI}, {ZERO, PI}},
111 {{PI_OVER_2, PI_OVER_2}, {ZERO, ZERO}, {ZERO, PI}},
112 {{PI_OVER_2, PI_OVER_2},
113 {PI_OVER_2, PI_OVER_2},
114 {PI_OVER_4, THREE_PI_OVER_4}},
115};
116
117} // namespace atan2_internal
118
119LIBC_INLINE double atan2(double y, double x) {
120 using namespace atan_internal;
121 using namespace atan2_internal;
122 using FPBits = fputil::FPBits<double>;
123
124 constexpr double IS_NEG[2] = {1.0, -1.0};
125
126 FPBits x_bits(x), y_bits(y);
127 bool x_sign = x_bits.sign().is_neg();
128 bool y_sign = y_bits.sign().is_neg();
129 x_bits = x_bits.abs();
130 y_bits = y_bits.abs();
131 uint64_t x_abs = x_bits.uintval();
132 uint64_t y_abs = y_bits.uintval();
133 bool recip = x_abs < y_abs;
134 uint64_t min_abs = recip ? x_abs : y_abs;
135 uint64_t max_abs = !recip ? x_abs : y_abs;
136 unsigned min_exp = static_cast<unsigned>(min_abs >> FPBits::FRACTION_LEN);
137 unsigned max_exp = static_cast<unsigned>(max_abs >> FPBits::FRACTION_LEN);
138
139 double num = FPBits(min_abs).get_val();
140 double den = FPBits(max_abs).get_val();
141
142 // Check for exceptional cases, whether inputs are 0, inf, nan, or close to
143 // overflow, or close to underflow.
144 if (LIBC_UNLIKELY(max_exp > 0x7ffU - 128U || min_exp < 128U)) {
145 if (x_bits.is_nan() || y_bits.is_nan()) {
146 if (x_bits.is_signaling_nan() || y_bits.is_signaling_nan())
147 fputil::raise_except_if_required(FE_INVALID);
148 return FPBits::quiet_nan().get_val();
149 }
150 unsigned x_except = x == 0.0 ? 0 : (FPBits(x_abs).is_inf() ? 2 : 1);
151 unsigned y_except = y == 0.0 ? 0 : (FPBits(y_abs).is_inf() ? 2 : 1);
152
153 if ((x_except != 1) || (y_except != 1)) {
154 DoubleDouble r = EXCEPTS[y_except][x_except][x_sign];
155 return fputil::multiply_add(x: IS_NEG[y_sign], y: r.hi, z: IS_NEG[y_sign] * r.lo);
156 }
157 bool scale_up = min_exp < 128U;
158 bool scale_down = max_exp > 0x7ffU - 128U;
159 // At least one input is denormal, multiply both numerator and denominator
160 // by some large enough power of 2 to normalize denormal inputs.
161 if (scale_up) {
162 num *= 0x1.0p64;
163 if (!scale_down)
164 den *= 0x1.0p64;
165 } else if (scale_down) {
166 den *= 0x1.0p-64;
167 if (!scale_up)
168 num *= 0x1.0p-64;
169 }
170
171 min_abs = FPBits(num).uintval();
172 max_abs = FPBits(den).uintval();
173 min_exp = static_cast<unsigned>(min_abs >> FPBits::FRACTION_LEN);
174 max_exp = static_cast<unsigned>(max_abs >> FPBits::FRACTION_LEN);
175 }
176
177 double final_sign = IS_NEG[(x_sign != y_sign) != recip];
178 DoubleDouble const_term = CONST_ADJ[x_sign][y_sign][recip];
179 unsigned exp_diff = max_exp - min_exp;
180 // We have the following bound for normalized n and d:
181 // 2^(-exp_diff - 1) < n/d < 2^(-exp_diff + 1).
182 if (LIBC_UNLIKELY(exp_diff > 54)) {
183 return fputil::multiply_add(x: final_sign, y: const_term.hi,
184 z: final_sign * (const_term.lo + num / den));
185 }
186
187 double k = fputil::nearest_integer(x: 64.0 * num / den);
188 unsigned idx = static_cast<unsigned>(k);
189 // k = idx / 64
190 k *= 0x1.0p-6;
191
192 // Range reduction:
193 // atan(n/d) - atan(k/64) = atan((n/d - k/64) / (1 + (n/d) * (k/64)))
194 // = atan((n - d * k/64)) / (d + n * k/64))
195 DoubleDouble num_k = fputil::exact_mult(a: num, b: k);
196 DoubleDouble den_k = fputil::exact_mult(a: den, b: k);
197
198 // num_dd = n - d * k
199 DoubleDouble num_dd = fputil::exact_add(a: num - den_k.hi, b: -den_k.lo);
200 // den_dd = d + n * k
201 DoubleDouble den_dd = fputil::exact_add(a: den, b: num_k.hi);
202 den_dd.lo += num_k.lo;
203
204 // q = (n - d * k) / (d + n * k)
205 DoubleDouble q = fputil::div(a: num_dd, b: den_dd);
206 // p ~ atan(q)
207 DoubleDouble p = atan_eval(x: q);
208
209 DoubleDouble r = fputil::add(a: const_term, b: fputil::add(a: ATAN_I[idx], b: p));
210 r.hi *= final_sign;
211 r.lo *= final_sign;
212
213 return r.hi + r.lo;
214}
215
216} // namespace math
217
218} // namespace LIBC_NAMESPACE_DECL
219
220#endif // LLVM_LIBC_SRC___SUPPORT_MATH_ATAN2_H
221