1//===-- Implementation header for atan2f128 ---------------------*- 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_ATAN2F128_H
10#define LLVM_LIBC_SRC___SUPPORT_MATH_ATAN2F128_H
11
12#include "atan_utils.h"
13#include "src/__support/FPUtil/FPBits.h"
14#include "src/__support/FPUtil/dyadic_float.h"
15#include "src/__support/FPUtil/float128.h"
16#include "src/__support/FPUtil/nearest_integer.h"
17#include "src/__support/integer_literals.h"
18#include "src/__support/macros/config.h"
19#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
20#include "src/__support/uint128.h"
21
22namespace LIBC_NAMESPACE_DECL {
23
24namespace math {
25
26using LIBC_NAMESPACE::fputil::Float128;
27
28// There are several range reduction steps we can take for atan2(y, x) as
29// follow:
30
31// * Range reduction 1: signness
32// atan2(y, x) will return a number between -PI and PI representing the angle
33// forming by the 0x axis and the vector (x, y) on the 0xy-plane.
34// In particular, we have that:
35// atan2(y, x) = atan( y/x ) if x >= 0 and y >= 0 (I-quadrant)
36// = pi + atan( y/x ) if x < 0 and y >= 0 (II-quadrant)
37// = -pi + atan( y/x ) if x < 0 and y < 0 (III-quadrant)
38// = atan( y/x ) if x >= 0 and y < 0 (IV-quadrant)
39// Since atan function is odd, we can use the formula:
40// atan(-u) = -atan(u)
41// to adjust the above conditions a bit further:
42// atan2(y, x) = atan( |y|/|x| ) if x >= 0 and y >= 0 (I-quadrant)
43// = pi - atan( |y|/|x| ) if x < 0 and y >= 0 (II-quadrant)
44// = -pi + atan( |y|/|x| ) if x < 0 and y < 0 (III-quadrant)
45// = -atan( |y|/|x| ) if x >= 0 and y < 0 (IV-quadrant)
46// Which can be simplified to:
47// atan2(y, x) = sign(y) * atan( |y|/|x| ) if x >= 0
48// = sign(y) * (pi - atan( |y|/|x| )) if x < 0
49
50// * Range reduction 2: reciprocal
51// Now that the argument inside atan is positive, we can use the formula:
52// atan(1/x) = pi/2 - atan(x)
53// to make the argument inside atan <= 1 as follow:
54// atan2(y, x) = sign(y) * atan( |y|/|x|) if 0 <= |y| <= x
55// = sign(y) * (pi/2 - atan( |x|/|y| ) if 0 <= x < |y|
56// = sign(y) * (pi - atan( |y|/|x| )) if 0 <= |y| <= -x
57// = sign(y) * (pi/2 + atan( |x|/|y| )) if 0 <= -x < |y|
58
59// * Range reduction 3: look up table.
60// After the previous two range reduction steps, we reduce the problem to
61// compute atan(u) with 0 <= u <= 1, or to be precise:
62// atan( n / d ) where n = min(|x|, |y|) and d = max(|x|, |y|).
63// An accurate polynomial approximation for the whole [0, 1] input range will
64// require a very large degree. To make it more efficient, we reduce the input
65// range further by finding an integer idx such that:
66// | n/d - idx/64 | <= 1/128.
67// In particular,
68// idx := round(2^6 * n/d)
69// Then for the fast pass, we find a polynomial approximation for:
70// atan( n/d ) ~ atan( idx/64 ) + (n/d - idx/64) * Q(n/d - idx/64)
71// For the accurate pass, we use the addition formula:
72// atan( n/d ) - atan( idx/64 ) = atan( (n/d - idx/64)/(1 + (n*idx)/(64*d)) )
73// = atan( (n - d*(idx/64))/(d + n*(idx/64)) )
74// And for the fast pass, we use degree-13 minimax polynomial to compute the
75// RHS:
76// atan(u) ~ P(u) = u - c_3 * u^3 + c_5 * u^5 - c_7 * u^7 + c_9 *u^9 -
77// - c_11 * u^11 + c_13 * u^13
78// with absolute errors bounded by:
79// |atan(u) - P(u)| < 2^-121
80// and relative errors bounded by:
81// |(atan(u) - P(u)) / P(u)| < 2^-114.
82
83LIBC_INLINE Float128 atan2f128(Float128 y, Float128 x) {
84 using DFloat128 = fputil::DyadicFloat<128>;
85
86 constexpr DFloat128 ZERO = {Sign::POS, 0, 0_u128};
87 constexpr DFloat128 MZERO = {Sign::NEG, 0, 0_u128};
88 constexpr DFloat128 PI = {Sign::POS, -126,
89 0xc90fdaa2'2168c234'c4c6628b'80dc1cd1_u128};
90 constexpr DFloat128 MPI = {Sign::NEG, -126,
91 0xc90fdaa2'2168c234'c4c6628b'80dc1cd1_u128};
92 constexpr DFloat128 PI_OVER_2 = {Sign::POS, -127,
93 0xc90fdaa2'2168c234'c4c6628b'80dc1cd1_u128};
94 constexpr DFloat128 MPI_OVER_2 = {Sign::NEG, -127,
95 0xc90fdaa2'2168c234'c4c6628b'80dc1cd1_u128};
96 constexpr DFloat128 PI_OVER_4 = {Sign::POS, -128,
97 0xc90fdaa2'2168c234'c4c6628b'80dc1cd1_u128};
98 constexpr DFloat128 THREE_PI_OVER_4 = {
99 Sign::POS, -126, 0x96cbe3f9'990e91a7'9394c9e8'a0a5159d_u128};
100
101 // Adjustment for constant term:
102 // CONST_ADJ[x_sign][y_sign][recip]
103 constexpr DFloat128 CONST_ADJ[2][2][2] = {
104 {{ZERO, MPI_OVER_2}, {MZERO, MPI_OVER_2}},
105 {{MPI, PI_OVER_2}, {MPI, PI_OVER_2}}};
106
107 using namespace atan_internal;
108 using FPBits = fputil::FPBits<Float128>;
109 using DFloat128 = fputil::DyadicFloat<128>;
110
111 FPBits x_bits(x), y_bits(y);
112 bool x_sign = x_bits.sign().is_neg();
113 bool y_sign = y_bits.sign().is_neg();
114 x_bits = x_bits.abs();
115 y_bits = y_bits.abs();
116 UInt128 x_abs = x_bits.uintval();
117 UInt128 y_abs = y_bits.uintval();
118 bool recip = x_abs < y_abs;
119 UInt128 min_abs = recip ? x_abs : y_abs;
120 UInt128 max_abs = !recip ? x_abs : y_abs;
121 unsigned min_exp = static_cast<unsigned>(min_abs >> FPBits::FRACTION_LEN);
122 unsigned max_exp = static_cast<unsigned>(max_abs >> FPBits::FRACTION_LEN);
123
124 DFloat128 num(FPBits(min_abs).get_val());
125 DFloat128 den(FPBits(max_abs).get_val());
126
127 // Check for exceptional cases, whether inputs are 0, inf, nan, or close to
128 // overflow, or close to underflow.
129 if (LIBC_UNLIKELY(max_exp >= 0x7fffU || min_exp == 0U)) {
130 if (x_bits.is_nan() || y_bits.is_nan())
131 return FPBits::quiet_nan().get_val();
132 unsigned x_except = x == Float128(0) ? 0 : (FPBits(x_abs).is_inf() ? 2 : 1);
133 unsigned y_except = y == Float128(0) ? 0 : (FPBits(y_abs).is_inf() ? 2 : 1);
134
135 // Exceptional cases:
136 // EXCEPT[y_except][x_except][x_is_neg]
137 // with x_except & y_except:
138 // 0: zero
139 // 1: finite, non-zero
140 // 2: infinity
141 constexpr DFloat128 EXCEPTS[3][3][2] = {
142 {{ZERO, PI}, {ZERO, PI}, {ZERO, PI}},
143 {{PI_OVER_2, PI_OVER_2}, {ZERO, ZERO}, {ZERO, PI}},
144 {{PI_OVER_2, PI_OVER_2},
145 {PI_OVER_2, PI_OVER_2},
146 {PI_OVER_4, THREE_PI_OVER_4}},
147 };
148
149 if ((x_except != 1) || (y_except != 1)) {
150 DFloat128 r = EXCEPTS[y_except][x_except][x_sign];
151 if (y_sign)
152 r.sign = r.sign.negate();
153 return r.template as<Float128, /*ShouldSignalExceptions=*/true>();
154 }
155 }
156
157 bool final_sign = ((x_sign != y_sign) != recip);
158 DFloat128 const_term = CONST_ADJ[x_sign][y_sign][recip];
159 int exp_diff = den.exponent - num.exponent;
160 // We have the following bound for normalized n and d:
161 // 2^(-exp_diff - 1) < n/d < 2^(-exp_diff + 1).
162 if (LIBC_UNLIKELY(exp_diff > FPBits::FRACTION_LEN + 2)) {
163 DFloat128 quotient = rounded_div(af: num, bf: den);
164 DFloat128 result = quick_add(a: const_term, b: quotient);
165 if (final_sign)
166 result.sign = result.sign.negate();
167 return result.template as<Float128, /*ShouldSignalExceptions=*/true>();
168 }
169
170 // Take 24 leading bits of num and den to convert to float for fast division.
171 // We also multiply the numerator by 64 using integer addition directly to the
172 // exponent field.
173 float num_f =
174 cpp::bit_cast<float>(from: static_cast<uint32_t>(num.mantissa >> 104) +
175 (6U << fputil::FPBits<float>::FRACTION_LEN));
176 float den_f = cpp::bit_cast<float>(
177 from: static_cast<uint32_t>(den.mantissa >> 104) +
178 (static_cast<uint32_t>(exp_diff) << fputil::FPBits<float>::FRACTION_LEN));
179
180 float k = fputil::nearest_integer(x: num_f / den_f);
181 unsigned idx = static_cast<unsigned>(k);
182
183 // k_f128 = idx / 64
184 DFloat128 k_f128(Sign::POS, -6, DFloat128::MantissaType(idx));
185
186 // Range reduction:
187 // atan(n/d) - atan(k) = atan((n/d - k/64) / (1 + (n/d) * (k/64)))
188 // = atan((n - d * k/64)) / (d + n * k/64))
189 // num_f128 = n - d * k/64
190 DFloat128 num_f128 = fputil::multiply_add(a: den, b: -k_f128, c: num);
191 // den_f128 = d + n * k/64
192 DFloat128 den_f128 = fputil::multiply_add(a: num, b: k_f128, c: den);
193
194 // q = (n - d * k) / (d + n * k)
195 DFloat128 q =
196 fputil::quick_mul(a: num_f128, b: fputil::approx_reciprocal(a: den_f128));
197 // p ~ atan(q)
198 DFloat128 p = atan_eval(x: q);
199
200 DFloat128 r =
201 fputil::quick_add(a: const_term, b: fputil::quick_add(a: ATAN_I_F128[idx], b: p));
202 if (final_sign)
203 r.sign = r.sign.negate();
204
205 return r.template as<Float128, /*ShouldSignalExceptions=*/true>();
206}
207
208} // namespace math
209
210} // namespace LIBC_NAMESPACE_DECL
211
212#endif // LLVM_LIBC_SRC___SUPPORT_MATH_ATAN2F128_H
213