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
83namespace atan2f128_internal {
84
85using DFloat128 = fputil::DyadicFloat<128>;
86
87LIBC_INLINE_VAR constexpr DFloat128 ZERO = {Sign::POS, 0, 0_u128};
88LIBC_INLINE_VAR constexpr DFloat128 MZERO = {Sign::NEG, 0, 0_u128};
89LIBC_INLINE_VAR constexpr DFloat128 PI = {
90 Sign::POS, -126, 0xc90fdaa2'2168c234'c4c6628b'80dc1cd1_u128};
91LIBC_INLINE_VAR constexpr DFloat128 MPI = {
92 Sign::NEG, -126, 0xc90fdaa2'2168c234'c4c6628b'80dc1cd1_u128};
93LIBC_INLINE_VAR constexpr DFloat128 PI_OVER_2 = {
94 Sign::POS, -127, 0xc90fdaa2'2168c234'c4c6628b'80dc1cd1_u128};
95LIBC_INLINE_VAR constexpr DFloat128 MPI_OVER_2 = {
96 Sign::NEG, -127, 0xc90fdaa2'2168c234'c4c6628b'80dc1cd1_u128};
97LIBC_INLINE_VAR constexpr DFloat128 PI_OVER_4 = {
98 Sign::POS, -128, 0xc90fdaa2'2168c234'c4c6628b'80dc1cd1_u128};
99LIBC_INLINE_VAR constexpr DFloat128 THREE_PI_OVER_4 = {
100 Sign::POS, -126, 0x96cbe3f9'990e91a7'9394c9e8'a0a5159d_u128};
101
102// Adjustment for constant term:
103// CONST_ADJ[x_sign][y_sign][recip]
104LIBC_INLINE_VAR constexpr DFloat128 CONST_ADJ[2][2][2] = {
105 {{ZERO, MPI_OVER_2}, {MZERO, MPI_OVER_2}},
106 {{MPI, PI_OVER_2}, {MPI, PI_OVER_2}}};
107
108// Exceptional cases:
109// EXCEPT[y_except][x_except][x_is_neg]
110// with x_except & y_except:
111// 0: zero
112// 1: finite, non-zero
113// 2: infinity
114LIBC_INLINE_VAR constexpr DFloat128 EXCEPTS[3][3][2] = {
115 {{ZERO, PI}, {ZERO, PI}, {ZERO, PI}},
116 {{PI_OVER_2, PI_OVER_2}, {ZERO, ZERO}, {ZERO, PI}},
117 {{PI_OVER_2, PI_OVER_2},
118 {PI_OVER_2, PI_OVER_2},
119 {PI_OVER_4, THREE_PI_OVER_4}},
120};
121
122} // namespace atan2f128_internal
123
124LIBC_INLINE Float128 atan2f128(Float128 y, Float128 x) {
125 using namespace atan_internal;
126 using namespace atan2f128_internal;
127 using FPBits = fputil::FPBits<Float128>;
128
129 FPBits x_bits(x), y_bits(y);
130 bool x_sign = x_bits.sign().is_neg();
131 bool y_sign = y_bits.sign().is_neg();
132 x_bits = x_bits.abs();
133 y_bits = y_bits.abs();
134 UInt128 x_abs = x_bits.uintval();
135 UInt128 y_abs = y_bits.uintval();
136 bool recip = x_abs < y_abs;
137 UInt128 min_abs = recip ? x_abs : y_abs;
138 UInt128 max_abs = !recip ? x_abs : y_abs;
139 unsigned min_exp = static_cast<unsigned>(min_abs >> FPBits::FRACTION_LEN);
140 unsigned max_exp = static_cast<unsigned>(max_abs >> FPBits::FRACTION_LEN);
141
142 DFloat128 num(FPBits(min_abs).get_val());
143 DFloat128 den(FPBits(max_abs).get_val());
144
145 // Check for exceptional cases, whether inputs are 0, inf, nan, or close to
146 // overflow, or close to underflow.
147 if (LIBC_UNLIKELY(max_exp >= 0x7fffU || min_exp == 0U)) {
148 if (x_bits.is_nan() || y_bits.is_nan())
149 return FPBits::quiet_nan().get_val();
150 unsigned x_except = x == Float128(0) ? 0 : (FPBits(x_abs).is_inf() ? 2 : 1);
151 unsigned y_except = y == Float128(0) ? 0 : (FPBits(y_abs).is_inf() ? 2 : 1);
152
153 if ((x_except != 1) || (y_except != 1)) {
154 DFloat128 r = EXCEPTS[y_except][x_except][x_sign];
155 if (y_sign)
156 r.sign = r.sign.negate();
157 return r.template as<Float128, /*ShouldSignalExceptions=*/true>();
158 }
159 }
160
161 bool final_sign = ((x_sign != y_sign) != recip);
162 DFloat128 const_term = CONST_ADJ[x_sign][y_sign][recip];
163 int exp_diff = den.exponent - num.exponent;
164 // We have the following bound for normalized n and d:
165 // 2^(-exp_diff - 1) < n/d < 2^(-exp_diff + 1).
166 if (LIBC_UNLIKELY(exp_diff > FPBits::FRACTION_LEN + 2)) {
167 DFloat128 quotient = rounded_div(af: num, bf: den);
168 DFloat128 result = quick_add(a: const_term, b: quotient);
169 if (final_sign)
170 result.sign = result.sign.negate();
171 return result.template as<Float128, /*ShouldSignalExceptions=*/true>();
172 }
173
174 // Take 24 leading bits of num and den to convert to float for fast division.
175 // We also multiply the numerator by 64 using integer addition directly to the
176 // exponent field.
177 float num_f =
178 cpp::bit_cast<float>(from: static_cast<uint32_t>(num.mantissa >> 104) +
179 (6U << fputil::FPBits<float>::FRACTION_LEN));
180 float den_f = cpp::bit_cast<float>(
181 from: static_cast<uint32_t>(den.mantissa >> 104) +
182 (static_cast<uint32_t>(exp_diff) << fputil::FPBits<float>::FRACTION_LEN));
183
184 float k = fputil::nearest_integer(x: num_f / den_f);
185 unsigned idx = static_cast<unsigned>(k);
186
187 // k_f128 = idx / 64
188 DFloat128 k_f128(Sign::POS, -6, DFloat128::MantissaType(idx));
189
190 // Range reduction:
191 // atan(n/d) - atan(k) = atan((n/d - k/64) / (1 + (n/d) * (k/64)))
192 // = atan((n - d * k/64)) / (d + n * k/64))
193 // num_f128 = n - d * k/64
194 DFloat128 num_f128 = fputil::sub_multiply(a: num, b: den, c: k_f128);
195 // den_f128 = d + n * k/64
196 DFloat128 den_f128 = fputil::multiply_add(a: num, b: k_f128, c: den);
197
198 // q = (n - d * k) / (d + n * k)
199 DFloat128 q =
200 fputil::quick_mul(a: num_f128, b: fputil::approx_reciprocal(a: den_f128));
201 // p ~ atan(q)
202 DFloat128 p = atan_eval(x: q);
203
204 DFloat128 r =
205 fputil::quick_add(a: const_term, b: fputil::quick_add(a: ATAN_I_F128[idx], b: p));
206 if (final_sign)
207 r.sign = r.sign.negate();
208
209 return r.template as<Float128, /*ShouldSignalExceptions=*/true>();
210}
211
212} // namespace math
213
214} // namespace LIBC_NAMESPACE_DECL
215
216#endif // LLVM_LIBC_SRC___SUPPORT_MATH_ATAN2F128_H
217