Skip to content

Commit ade502a

Browse files
authored
[libc][math] Implement double precision asin correctly rounded for all rounding modes. (llvm#134401)
Main algorithm: The Taylor series expansion of `asin(x)` is: ```math \begin{align*} asin(x) &= x + x^3 / 6 + 3x^5 / 40 + ... \\ &= x \cdot P(x^2) \\ &= x \cdot P(u) &\text{, where } u = x^2. \end{align*} ``` For the fast path, we perform range reduction mod 1/64 and use degree-7 (minimax + Taylor) polynomials to approximate `P(x^2)`. When `|x| >= 0.5`, we use the transformation: ```math u = \frac{1 + x}{2} ``` and apply half-angle formula to reduce `asin(x)` to: ```math \begin{align*} asin(x) &= sign(x) \cdot \left( \frac{\pi}{2} - 2 \cdot asin(\sqrt{u}) \right) \\ &= sign(x) \cdot \left( \frac{\pi}{2} - 2 \cdot \sqrt{u} \cdot P(u) \right). \end{align*} ``` Since `0.5 <= |x| <= 1`, `|u| <= 0.5`. So we can reuse the polynomial evaluation of `P(u)` when `|x| < 0.5`. For the accurate path, we redo the computations in 128-bit precision with degree-15 (minimax + Taylor) polynomials to approximate `P(u)`.
1 parent 1ff931e commit ade502a

File tree

14 files changed

+1049
-1
lines changed

14 files changed

+1049
-1
lines changed

libc/config/darwin/arm/entrypoints.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@ set(TARGET_LIBM_ENTRYPOINTS
137137
# math.h entrypoints
138138
libc.src.math.acosf
139139
libc.src.math.acoshf
140+
libc.src.math.asin
140141
libc.src.math.asinf
141142
libc.src.math.asinhf
142143
libc.src.math.atan2

libc/config/linux/aarch64/entrypoints.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,7 @@ set(TARGET_LIBM_ENTRYPOINTS
412412
# math.h entrypoints
413413
libc.src.math.acosf
414414
libc.src.math.acoshf
415+
libc.src.math.asin
415416
libc.src.math.asinf
416417
libc.src.math.asinhf
417418
libc.src.math.atan2

libc/config/linux/arm/entrypoints.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,7 @@ set(TARGET_LIBM_ENTRYPOINTS
244244
# math.h entrypoints
245245
libc.src.math.acosf
246246
libc.src.math.acoshf
247+
libc.src.math.asin
247248
libc.src.math.asinf
248249
libc.src.math.asinhf
249250
libc.src.math.atan2

libc/config/linux/riscv/entrypoints.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,7 @@ set(TARGET_LIBM_ENTRYPOINTS
398398
# math.h entrypoints
399399
libc.src.math.acosf
400400
libc.src.math.acoshf
401+
libc.src.math.asin
401402
libc.src.math.asinf
402403
libc.src.math.asinhf
403404
libc.src.math.atan2

libc/config/linux/x86_64/entrypoints.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,7 @@ set(TARGET_LIBM_ENTRYPOINTS
417417
# math.h entrypoints
418418
libc.src.math.acosf
419419
libc.src.math.acoshf
420+
libc.src.math.asin
420421
libc.src.math.asinf
421422
libc.src.math.asinhf
422423
libc.src.math.atan2

libc/config/windows/entrypoints.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ set(TARGET_LIBM_ENTRYPOINTS
129129
# math.h entrypoints
130130
libc.src.math.acosf
131131
libc.src.math.acoshf
132+
libc.src.math.asin
132133
libc.src.math.asinf
133134
libc.src.math.asinhf
134135
libc.src.math.atan2

libc/docs/headers/math/index.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ Higher Math Functions
255255
+-----------+------------------+-----------------+------------------------+----------------------+------------------------+------------------------+----------------------------+
256256
| acospi | | | | |check| | | 7.12.4.8 | F.10.1.8 |
257257
+-----------+------------------+-----------------+------------------------+----------------------+------------------------+------------------------+----------------------------+
258-
| asin | |check| | | | |check| | | 7.12.4.2 | F.10.1.2 |
258+
| asin | |check| | |check| | | | | 7.12.4.2 | F.10.1.2 |
259259
+-----------+------------------+-----------------+------------------------+----------------------+------------------------+------------------------+----------------------------+
260260
| asinh | |check| | | | |check| | | 7.12.5.2 | F.10.2.2 |
261261
+-----------+------------------+-----------------+------------------------+----------------------+------------------------+------------------------+----------------------------+

libc/src/math/generic/CMakeLists.txt

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4096,6 +4096,38 @@ add_entrypoint_object(
40964096
libc.src.__support.macros.properties.types
40974097
)
40984098

4099+
add_header_library(
4100+
asin_utils
4101+
HDRS
4102+
atan_utils.h
4103+
DEPENDS
4104+
libc.src.__support.integer_literals
4105+
libc.src.__support.FPUtil.double_double
4106+
libc.src.__support.FPUtil.dyadic_float
4107+
libc.src.__support.FPUtil.multiply_add
4108+
libc.src.__support.FPUtil.nearest_integer
4109+
libc.src.__support.FPUtil.polyeval
4110+
libc.src.__support.macros.optimization
4111+
)
4112+
4113+
add_entrypoint_object(
4114+
asin
4115+
SRCS
4116+
asin.cpp
4117+
HDRS
4118+
../asin.h
4119+
DEPENDS
4120+
libc.src.__support.FPUtil.double_double
4121+
libc.src.__support.FPUtil.dyadic_float
4122+
libc.src.__support.FPUtil.fenv_impl
4123+
libc.src.__support.FPUtil.fp_bits
4124+
libc.src.__support.FPUtil.multiply_add
4125+
libc.src.__support.FPUtil.polyeval
4126+
libc.src.__support.FPUtil.sqrt
4127+
libc.src.__support.macros.optimization
4128+
libc.src.__support.macros.properties.cpu_features
4129+
)
4130+
40994131
add_entrypoint_object(
41004132
acosf
41014133
SRCS

libc/src/math/generic/asin.cpp

Lines changed: 286 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,286 @@
1+
//===-- Double-precision asin 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/asin.h"
10+
#include "asin_utils.h"
11+
#include "src/__support/FPUtil/FEnvImpl.h"
12+
#include "src/__support/FPUtil/FPBits.h"
13+
#include "src/__support/FPUtil/PolyEval.h"
14+
#include "src/__support/FPUtil/double_double.h"
15+
#include "src/__support/FPUtil/dyadic_float.h"
16+
#include "src/__support/FPUtil/multiply_add.h"
17+
#include "src/__support/FPUtil/sqrt.h"
18+
#include "src/__support/macros/config.h"
19+
#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
20+
#include "src/__support/macros/properties/cpu_features.h" // LIBC_TARGET_CPU_HAS_FMA
21+
22+
namespace LIBC_NAMESPACE_DECL {
23+
24+
using DoubleDouble = fputil::DoubleDouble;
25+
using Float128 = fputil::DyadicFloat<128>;
26+
27+
LLVM_LIBC_FUNCTION(double, asin, (double x)) {
28+
using FPBits = fputil::FPBits<double>;
29+
30+
FPBits xbits(x);
31+
int x_exp = xbits.get_biased_exponent();
32+
33+
// |x| < 0.5.
34+
if (x_exp < FPBits::EXP_BIAS - 1) {
35+
// |x| < 2^-26.
36+
if (LIBC_UNLIKELY(x_exp < FPBits::EXP_BIAS - 26)) {
37+
// When |x| < 2^-26, the relative error of the approximation asin(x) ~ x
38+
// is:
39+
// |asin(x) - x| / |asin(x)| < |x^3| / (6|x|)
40+
// = x^2 / 6
41+
// < 2^-54
42+
// < epsilon(1)/2.
43+
// So the correctly rounded values of asin(x) are:
44+
// = x + sign(x)*eps(x) if rounding mode = FE_TOWARDZERO,
45+
// or (rounding mode = FE_UPWARD and x is
46+
// negative),
47+
// = x otherwise.
48+
// To simplify the rounding decision and make it more efficient, we use
49+
// fma(x, 2^-54, x) instead.
50+
// Note: to use the formula x + 2^-54*x to decide the correct rounding, we
51+
// do need fma(x, 2^-54, x) to prevent underflow caused by 2^-54*x when
52+
// |x| < 2^-1022. For targets without FMA instructions, when x is close to
53+
// denormal range, we normalize x,
54+
#if defined(LIBC_MATH_HAS_SKIP_ACCURATE_PASS)
55+
return x;
56+
#elif defined(LIBC_TARGET_CPU_HAS_FMA_DOUBLE)
57+
return fputil::multiply_add(x, 0x1.0p-54, x);
58+
#else
59+
if (xbits.abs().uintval() == 0)
60+
return x;
61+
// Get sign(x) * min_normal.
62+
FPBits eps_bits = FPBits::min_normal();
63+
eps_bits.set_sign(xbits.sign());
64+
double eps = eps_bits.get_val();
65+
double normalize_const = (x_exp == 0) ? eps : 0.0;
66+
double scaled_normal =
67+
fputil::multiply_add(x + normalize_const, 0x1.0p54, eps);
68+
return fputil::multiply_add(scaled_normal, 0x1.0p-54, -normalize_const);
69+
#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
70+
}
71+
72+
#ifdef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
73+
return x * asin_eval(x * x);
74+
#else
75+
unsigned idx;
76+
DoubleDouble x_sq = fputil::exact_mult(x, x);
77+
double err = x * 0x1.0p-51;
78+
// Polynomial approximation:
79+
// p ~ asin(x)/x
80+
81+
DoubleDouble p = asin_eval(x_sq, idx, err);
82+
// asin(x) ~ x * (ASIN_COEFFS[idx][0] + p)
83+
DoubleDouble r0 = fputil::exact_mult(x, p.hi);
84+
double r_lo = fputil::multiply_add(x, p.lo, r0.lo);
85+
86+
// Ziv's accuracy test.
87+
88+
double r_upper = r0.hi + (r_lo + err);
89+
double r_lower = r0.hi + (r_lo - err);
90+
91+
if (LIBC_LIKELY(r_upper == r_lower))
92+
return r_upper;
93+
94+
// Ziv's accuracy test failed, perform 128-bit calculation.
95+
96+
// Recalculate mod 1/64.
97+
idx = static_cast<unsigned>(fputil::nearest_integer(x_sq.hi * 0x1.0p6));
98+
99+
// Get x^2 - idx/64 exactly. When FMA is available, double-double
100+
// multiplication will be correct for all rounding modes. Otherwise we use
101+
// Float128 directly.
102+
Float128 x_f128(x);
103+
104+
#ifdef LIBC_TARGET_CPU_HAS_FMA_DOUBLE
105+
// u = x^2 - idx/64
106+
Float128 u_hi(
107+
fputil::multiply_add(static_cast<double>(idx), -0x1.0p-6, x_sq.hi));
108+
Float128 u = fputil::quick_add(u_hi, Float128(x_sq.lo));
109+
#else
110+
Float128 x_sq_f128 = fputil::quick_mul(x_f128, x_f128);
111+
Float128 u = fputil::quick_add(
112+
x_sq_f128, Float128(static_cast<double>(idx) * (-0x1.0p-6)));
113+
#endif // LIBC_TARGET_CPU_HAS_FMA_DOUBLE
114+
115+
Float128 p_f128 = asin_eval(u, idx);
116+
Float128 r = fputil::quick_mul(x_f128, p_f128);
117+
118+
return static_cast<double>(r);
119+
#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
120+
}
121+
// |x| >= 0.5
122+
123+
double x_abs = xbits.abs().get_val();
124+
125+
// Maintaining the sign:
126+
constexpr double SIGN[2] = {1.0, -1.0};
127+
double x_sign = SIGN[xbits.is_neg()];
128+
129+
// |x| >= 1
130+
if (LIBC_UNLIKELY(x_exp >= FPBits::EXP_BIAS)) {
131+
// x = +-1, asin(x) = +- pi/2
132+
if (x_abs == 1.0) {
133+
// return +- pi/2
134+
return fputil::multiply_add(x_sign, PI_OVER_TWO.hi,
135+
x_sign * PI_OVER_TWO.lo);
136+
}
137+
// |x| > 1, return NaN.
138+
if (xbits.is_finite()) {
139+
fputil::set_errno_if_required(EDOM);
140+
fputil::raise_except_if_required(FE_INVALID);
141+
} else if (xbits.is_signaling_nan()) {
142+
fputil::raise_except_if_required(FE_INVALID);
143+
}
144+
return FPBits::quiet_nan().get_val();
145+
}
146+
147+
// When |x| >= 0.5, we perform range reduction as follow:
148+
//
149+
// Assume further that 0.5 <= x < 1, and let:
150+
// y = asin(x)
151+
// We will use the double angle formula:
152+
// cos(2y) = 1 - 2 sin^2(y)
153+
// and the complement angle identity:
154+
// x = sin(y) = cos(pi/2 - y)
155+
// = 1 - 2 sin^2 (pi/4 - y/2)
156+
// So:
157+
// sin(pi/4 - y/2) = sqrt( (1 - x)/2 )
158+
// And hence:
159+
// pi/4 - y/2 = asin( sqrt( (1 - x)/2 ) )
160+
// Equivalently:
161+
// asin(x) = y = pi/2 - 2 * asin( sqrt( (1 - x)/2 ) )
162+
// Let u = (1 - x)/2, then:
163+
// asin(x) = pi/2 - 2 * asin( sqrt(u) )
164+
// Moreover, since 0.5 <= x < 1:
165+
// 0 < u <= 1/4, and 0 < sqrt(u) <= 0.5,
166+
// And hence we can reuse the same polynomial approximation of asin(x) when
167+
// |x| <= 0.5:
168+
// asin(x) ~ pi/2 - 2 * sqrt(u) * P(u),
169+
170+
// u = (1 - |x|)/2
171+
double u = fputil::multiply_add(x_abs, -0.5, 0.5);
172+
// v_hi + v_lo ~ sqrt(u).
173+
// Let:
174+
// h = u - v_hi^2 = (sqrt(u) - v_hi) * (sqrt(u) + v_hi)
175+
// Then:
176+
// sqrt(u) = v_hi + h / (sqrt(u) + v_hi)
177+
// ~ v_hi + h / (2 * v_hi)
178+
// So we can use:
179+
// v_lo = h / (2 * v_hi).
180+
// Then,
181+
// asin(x) ~ pi/2 - 2*(v_hi + v_lo) * P(u)
182+
double v_hi = fputil::sqrt<double>(u);
183+
184+
#ifdef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
185+
double p = asin_eval(u);
186+
double r = x_sign * fputil::multiply_add(-2.0 * v_hi, p, PI_OVER_TWO.hi);
187+
return r;
188+
#else
189+
190+
#ifdef LIBC_TARGET_CPU_HAS_FMA_DOUBLE
191+
double h = fputil::multiply_add(v_hi, -v_hi, u);
192+
#else
193+
DoubleDouble v_hi_sq = fputil::exact_mult(v_hi, v_hi);
194+
double h = (u - v_hi_sq.hi) - v_hi_sq.lo;
195+
#endif // LIBC_TARGET_CPU_HAS_FMA_DOUBLE
196+
197+
// Scale v_lo and v_hi by 2 from the formula:
198+
// vh = v_hi * 2
199+
// vl = 2*v_lo = h / v_hi.
200+
double vh = v_hi * 2.0;
201+
double vl = h / v_hi;
202+
203+
// Polynomial approximation:
204+
// p ~ asin(sqrt(u))/sqrt(u)
205+
unsigned idx;
206+
double err = vh * 0x1.0p-51;
207+
208+
DoubleDouble p = asin_eval(DoubleDouble{0.0, u}, idx, err);
209+
210+
// Perform computations in double-double arithmetic:
211+
// asin(x) = pi/2 - (v_hi + v_lo) * (ASIN_COEFFS[idx][0] + p)
212+
DoubleDouble r0 = fputil::quick_mult(DoubleDouble{vl, vh}, p);
213+
DoubleDouble r = fputil::exact_add(PI_OVER_TWO.hi, -r0.hi);
214+
215+
double r_lo = PI_OVER_TWO.lo - r0.lo + r.lo;
216+
217+
// Ziv's accuracy test.
218+
219+
#ifdef LIBC_TARGET_CPU_HAS_FMA_DOUBLE
220+
double r_upper = fputil::multiply_add(
221+
r.hi, x_sign, fputil::multiply_add(r_lo, x_sign, err));
222+
double r_lower = fputil::multiply_add(
223+
r.hi, x_sign, fputil::multiply_add(r_lo, x_sign, -err));
224+
#else
225+
r_lo *= x_sign;
226+
r.hi *= x_sign;
227+
double r_upper = r.hi + (r_lo + err);
228+
double r_lower = r.hi + (r_lo - err);
229+
#endif // LIBC_TARGET_CPU_HAS_FMA_DOUBLE
230+
231+
if (LIBC_LIKELY(r_upper == r_lower))
232+
return r_upper;
233+
234+
// Ziv's accuracy test failed, we redo the computations in Float128.
235+
// Recalculate mod 1/64.
236+
idx = static_cast<unsigned>(fputil::nearest_integer(u * 0x1.0p6));
237+
238+
// After the first step of Newton-Raphson approximating v = sqrt(u), we have
239+
// that:
240+
// sqrt(u) = v_hi + h / (sqrt(u) + v_hi)
241+
// v_lo = h / (2 * v_hi)
242+
// With error:
243+
// sqrt(u) - (v_hi + v_lo) = h * ( 1/(sqrt(u) + v_hi) - 1/(2*v_hi) )
244+
// = -h^2 / (2*v * (sqrt(u) + v)^2).
245+
// Since:
246+
// (sqrt(u) + v_hi)^2 ~ (2sqrt(u))^2 = 4u,
247+
// we can add another correction term to (v_hi + v_lo) that is:
248+
// v_ll = -h^2 / (2*v_hi * 4u)
249+
// = -v_lo * (h / 4u)
250+
// = -vl * (h / 8u),
251+
// making the errors:
252+
// sqrt(u) - (v_hi + v_lo + v_ll) = O(h^3)
253+
// well beyond 128-bit precision needed.
254+
255+
// Get the rounding error of vl = 2 * v_lo ~ h / vh
256+
// Get full product of vh * vl
257+
#ifdef LIBC_TARGET_CPU_HAS_FMA_DOUBLE
258+
double vl_lo = fputil::multiply_add(-v_hi, vl, h) / v_hi;
259+
#else
260+
DoubleDouble vh_vl = fputil::exact_mult(v_hi, vl);
261+
double vl_lo = ((h - vh_vl.hi) - vh_vl.lo) / v_hi;
262+
#endif // LIBC_TARGET_CPU_HAS_FMA_DOUBLE
263+
// vll = 2*v_ll = -vl * (h / (4u)).
264+
double t = h * (-0.25) / u;
265+
double vll = fputil::multiply_add(vl, t, vl_lo);
266+
// m_v = -(v_hi + v_lo + v_ll).
267+
Float128 m_v = fputil::quick_add(
268+
Float128(vh), fputil::quick_add(Float128(vl), Float128(vll)));
269+
m_v.sign = Sign::NEG;
270+
271+
// Perform computations in Float128:
272+
// asin(x) = pi/2 - (v_hi + v_lo + vll) * P(u).
273+
Float128 y_f128(fputil::multiply_add(static_cast<double>(idx), -0x1.0p-6, u));
274+
275+
Float128 p_f128 = asin_eval(y_f128, idx);
276+
Float128 r0_f128 = fputil::quick_mul(m_v, p_f128);
277+
Float128 r_f128 = fputil::quick_add(PI_OVER_TWO_F128, r0_f128);
278+
279+
if (xbits.is_neg())
280+
r_f128.sign = Sign::NEG;
281+
282+
return static_cast<double>(r_f128);
283+
#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
284+
}
285+
286+
} // namespace LIBC_NAMESPACE_DECL

0 commit comments

Comments
 (0)