pxfm/acos.rs
1/*
2 * // Copyright (c) Radzivon Bartoshyk 6/2025. All rights reserved.
3 * //
4 * // Redistribution and use in source and binary forms, with or without modification,
5 * // are permitted provided that the following conditions are met:
6 * //
7 * // 1. Redistributions of source code must retain the above copyright notice, this
8 * // list of conditions and the following disclaimer.
9 * //
10 * // 2. Redistributions in binary form must reproduce the above copyright notice,
11 * // this list of conditions and the following disclaimer in the documentation
12 * // and/or other materials provided with the distribution.
13 * //
14 * // 3. Neither the name of the copyright holder nor the names of its
15 * // contributors may be used to endorse or promote products derived from
16 * // this software without specific prior written permission.
17 * //
18 * // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 * // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22 * // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24 * // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 * // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26 * // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29use crate::acospi::PI_OVER_TWO_F128;
30use crate::asin::asin_eval;
31use crate::asin_eval_dyadic::asin_eval_dyadic;
32use crate::common::f_fmla;
33use crate::double_double::DoubleDouble;
34use crate::dyadic_float::{DyadicFloat128, DyadicSign};
35use crate::round::RoundFinite;
36
37/// Computes acos(x)
38///
39/// Max found ULP 0.5
40pub fn f_acos(x: f64) -> f64 {
41 let x_e = (x.to_bits() >> 52) & 0x7ff;
42 const E_BIAS: u64 = (1u64 << (11 - 1u64)) - 1u64;
43
44 const PI_OVER_TWO: DoubleDouble = DoubleDouble::new(
45 f64::from_bits(0x3c91a62633145c07),
46 f64::from_bits(0x3ff921fb54442d18),
47 );
48
49 let x_abs = f64::from_bits(x.to_bits() & 0x7fff_ffff_ffff_ffff);
50
51 // |x| < 0.5.
52 if x_e < E_BIAS - 1 {
53 // |x| < 2^-55.
54 if x_e < E_BIAS - 55 {
55 // When |x| < 2^-55, acos(x) = pi/2
56 return (x_abs + f64::from_bits(0x35f0000000000000)) + PI_OVER_TWO.hi;
57 }
58
59 let x_sq = DoubleDouble::from_exact_mult(x, x);
60 let err = x_abs * f64::from_bits(0x3cc0000000000000);
61 // Polynomial approximation:
62 // p ~ asin(x)/x
63 let (p, err) = asin_eval(x_sq, err);
64 // asin(x) ~ x * p
65 let r0 = DoubleDouble::from_exact_mult(x, p.hi);
66 // acos(x) = pi/2 - asin(x)
67 // ~ pi/2 - x * p
68 // = pi/2 - x * (p.hi + p.lo)
69 let r_hi = f_fmla(-x, p.hi, PI_OVER_TWO.hi);
70 // Use Dekker's 2SUM algorithm to compute the lower part.
71 let mut r_lo = ((PI_OVER_TWO.hi - r_hi) - r0.hi) - r0.lo;
72 r_lo = f_fmla(-x, p.lo, r_lo + PI_OVER_TWO.lo);
73
74 let r_upper = r_hi + (r_lo + err);
75 let r_lower = r_hi + (r_lo - err);
76
77 if r_upper == r_lower {
78 return r_upper;
79 }
80
81 return acos_less_0p5_hard(x, x_sq);
82 }
83
84 // |x| >= 0.5
85
86 let x_sign = if x.is_sign_negative() { -1.0 } else { 1.0 };
87
88 const PI: DoubleDouble = DoubleDouble::new(
89 f64::from_bits(0x3ca1a62633145c07),
90 f64::from_bits(0x400921fb54442d18),
91 );
92
93 // |x| >= 1
94 if x_e >= E_BIAS {
95 // x = +-1, asin(x) = +- pi/2
96 if x_abs == 1.0 {
97 // x = 1, acos(x) = 0,
98 // x = -1, acos(x) = pi
99 return if x == 1.0 {
100 0.0
101 } else {
102 f_fmla(-x_sign, PI.hi, PI.lo)
103 };
104 }
105 // |x| > 1, return NaN.
106 return f64::NAN;
107 }
108
109 // When |x| >= 0.5, we perform range reduction as follow:
110 //
111 // When 0.5 <= x < 1, let:
112 // y = acos(x)
113 // We will use the double angle formula:
114 // cos(2y) = 1 - 2 sin^2(y)
115 // and the complement angle identity:
116 // x = cos(y) = 1 - 2 sin^2 (y/2)
117 // So:
118 // sin(y/2) = sqrt( (1 - x)/2 )
119 // And hence:
120 // y/2 = asin( sqrt( (1 - x)/2 ) )
121 // Equivalently:
122 // acos(x) = y = 2 * asin( sqrt( (1 - x)/2 ) )
123 // Let u = (1 - x)/2, then:
124 // acos(x) = 2 * asin( sqrt(u) )
125 // Moreover, since 0.5 <= x < 1:
126 // 0 < u <= 1/4, and 0 < sqrt(u) <= 0.5,
127 // And hence we can reuse the same polynomial approximation of asin(x) when
128 // |x| <= 0.5:
129 // acos(x) ~ 2 * sqrt(u) * P(u).
130 //
131 // When -1 < x <= -0.5, we reduce to the previous case using the formula:
132 // acos(x) = pi - acos(-x)
133 // = pi - 2 * asin ( sqrt( (1 + x)/2 ) )
134 // ~ pi - 2 * sqrt(u) * P(u),
135 // where u = (1 - |x|)/2.
136
137 // u = (1 - |x|)/2
138 let u = f_fmla(x_abs, -0.5, 0.5);
139 // v_hi + v_lo ~ sqrt(u).
140 // Let:
141 // h = u - v_hi^2 = (sqrt(u) - v_hi) * (sqrt(u) + v_hi)
142 // Then:
143 // sqrt(u) = v_hi + h / (sqrt(u) + v_hi)
144 // ~ v_hi + h / (2 * v_hi)
145 // So we can use:
146 // v_lo = h / (2 * v_hi).
147 let v_hi = u.sqrt();
148
149 let h;
150 #[cfg(any(
151 all(
152 any(target_arch = "x86", target_arch = "x86_64"),
153 target_feature = "fma"
154 ),
155 all(target_arch = "aarch64", target_feature = "neon")
156 ))]
157 {
158 h = f_fmla(v_hi, -v_hi, u);
159 }
160 #[cfg(not(any(
161 all(
162 any(target_arch = "x86", target_arch = "x86_64"),
163 target_feature = "fma"
164 ),
165 all(target_arch = "aarch64", target_feature = "neon")
166 )))]
167 {
168 let v_hi_sq = DoubleDouble::from_exact_mult(v_hi, v_hi);
169 h = (u - v_hi_sq.hi) - v_hi_sq.lo;
170 }
171
172 // Scale v_lo and v_hi by 2 from the formula:
173 // vh = v_hi * 2
174 // vl = 2*v_lo = h / v_hi.
175 let vh = v_hi * 2.0;
176 let vl = h / v_hi;
177
178 // Polynomial approximation:
179 // p ~ asin(sqrt(u))/sqrt(u)
180 let err = vh * f64::from_bits(0x3cc0000000000000);
181
182 let (p, err) = asin_eval(DoubleDouble::new(0.0, u), err);
183
184 // Perform computations in double-double arithmetic:
185 // asin(x) = pi/2 - (v_hi + v_lo) * (ASIN_COEFFS[idx][0] + p)
186 let r0 = DoubleDouble::quick_mult(DoubleDouble::new(vl, vh), p);
187
188 let r_hi;
189 let r_lo;
190 if x.is_sign_positive() {
191 r_hi = r0.hi;
192 r_lo = r0.lo;
193 } else {
194 let r = DoubleDouble::from_exact_add(PI.hi, -r0.hi);
195 r_hi = r.hi;
196 r_lo = (PI.lo - r0.lo) + r.lo;
197 }
198
199 let r_upper = r_hi + (r_lo + err);
200 let r_lower = r_hi + (r_lo - err);
201
202 if r_upper == r_lower {
203 return r_upper;
204 }
205
206 acos_hard(x, u, v_hi, h, vh, vl)
207}
208
209#[cold]
210#[inline(never)]
211fn acos_hard(x: f64, u: f64, v_hi: f64, h: f64, vh: f64, vl: f64) -> f64 {
212 // Ziv's accuracy test failed, we redo the computations in Float128.
213 // Recalculate mod 1/64.
214 let idx = (u * f64::from_bits(0x4050000000000000)).round_finite() as usize;
215
216 // After the first step of Newton-Raphson approximating v = sqrt(u), we have
217 // that:
218 // sqrt(u) = v_hi + h / (sqrt(u) + v_hi)
219 // v_lo = h / (2 * v_hi)
220 // With error:
221 // sqrt(u) - (v_hi + v_lo) = h * ( 1/(sqrt(u) + v_hi) - 1/(2*v_hi) )
222 // = -h^2 / (2*v * (sqrt(u) + v)^2).
223 // Since:
224 // (sqrt(u) + v_hi)^2 ~ (2sqrt(u))^2 = 4u,
225 // we can add another correction term to (v_hi + v_lo) that is:
226 // v_ll = -h^2 / (2*v_hi * 4u)
227 // = -v_lo * (h / 4u)
228 // = -vl * (h / 8u),
229 // making the errors:
230 // sqrt(u) - (v_hi + v_lo + v_ll) = O(h^3)
231 // well beyond 128-bit precision needed.
232
233 // Get the rounding error of vl = 2 * v_lo ~ h / vh
234 // Get full product of vh * vl
235 let vl_lo;
236 #[cfg(any(
237 all(
238 any(target_arch = "x86", target_arch = "x86_64"),
239 target_feature = "fma"
240 ),
241 all(target_arch = "aarch64", target_feature = "neon")
242 ))]
243 {
244 vl_lo = f_fmla(-v_hi, vl, h) / v_hi;
245 }
246 #[cfg(not(any(
247 all(
248 any(target_arch = "x86", target_arch = "x86_64"),
249 target_feature = "fma"
250 ),
251 all(target_arch = "aarch64", target_feature = "neon")
252 )))]
253 {
254 let vh_vl = DoubleDouble::from_exact_mult(v_hi, vl);
255 vl_lo = ((h - vh_vl.hi) - vh_vl.lo) / v_hi;
256 }
257 let t = h * (-0.25) / u;
258 let vll = f_fmla(vl, t, vl_lo);
259 let m_v_p = DyadicFloat128::new_from_f64(vl) + DyadicFloat128::new_from_f64(vll);
260 let mut m_v = DyadicFloat128::new_from_f64(vh) + m_v_p;
261 m_v.sign = if x.is_sign_negative() {
262 DyadicSign::Neg
263 } else {
264 DyadicSign::Pos
265 };
266
267 // Perform computations in Float128:
268 // acos(x) = (v_hi + v_lo + vll) * P(u) , when 0.5 <= x < 1,
269 // = pi - (v_hi + v_lo + vll) * P(u) , when -1 < x <= -0.5.
270 let y_f128 =
271 DyadicFloat128::new_from_f64(f_fmla(idx as f64, f64::from_bits(0xbf90000000000000), u));
272
273 let p_f128 = asin_eval_dyadic(y_f128, idx);
274 let mut r_f128 = m_v * p_f128;
275
276 if x.is_sign_negative() {
277 const PI_F128: DyadicFloat128 = DyadicFloat128 {
278 sign: DyadicSign::Pos,
279 exponent: -126,
280 mantissa: 0xc90fdaa2_2168c234_c4c6628b_80dc1cd1_u128,
281 };
282 r_f128 = PI_F128 + r_f128;
283 }
284
285 r_f128.fast_as_f64()
286}
287
288#[cold]
289#[inline(never)]
290fn acos_less_0p5_hard(x: f64, x_sq: DoubleDouble) -> f64 {
291 // Ziv's accuracy test failed, perform 128-bit calculation.
292
293 // Recalculate mod 1/64.
294 let idx = (x_sq.hi * f64::from_bits(0x4050000000000000)).round_finite() as usize;
295
296 // Get x^2 - idx/64 exactly. When FMA is available, double-double
297 // multiplication will be correct for all rounding modes. Otherwise, we use
298 // Float128 directly.
299 let mut x_f128 = DyadicFloat128::new_from_f64(x);
300
301 let u: DyadicFloat128;
302 #[cfg(any(
303 all(
304 any(target_arch = "x86", target_arch = "x86_64"),
305 target_feature = "fma"
306 ),
307 all(target_arch = "aarch64", target_feature = "neon")
308 ))]
309 {
310 // u = x^2 - idx/64
311 let u_hi = DyadicFloat128::new_from_f64(f_fmla(
312 idx as f64,
313 f64::from_bits(0xbf90000000000000),
314 x_sq.hi,
315 ));
316 u = u_hi.quick_add(&DyadicFloat128::new_from_f64(x_sq.lo));
317 }
318
319 #[cfg(not(any(
320 all(
321 any(target_arch = "x86", target_arch = "x86_64"),
322 target_feature = "fma"
323 ),
324 all(target_arch = "aarch64", target_feature = "neon")
325 )))]
326 {
327 let x_sq_f128 = x_f128.quick_mul(&x_f128);
328 u = x_sq_f128.quick_add(&DyadicFloat128::new_from_f64(
329 idx as f64 * f64::from_bits(0xbf90000000000000),
330 ));
331 }
332
333 let p_f128 = asin_eval_dyadic(u, idx);
334 // Flip the sign of x_f128 to perform subtraction.
335 x_f128.sign = x_f128.sign.negate();
336 let r = PI_OVER_TWO_F128.quick_add(&x_f128.quick_mul(&p_f128));
337 r.fast_as_f64()
338}
339
340#[cfg(test)]
341mod tests {
342 use super::*;
343 #[test]
344 fn f_acos_test() {
345 assert_eq!(f_acos(0.7), 0.7953988301841436);
346 assert_eq!(f_acos(-0.1), 1.6709637479564565);
347 assert_eq!(f_acos(-0.4), 1.9823131728623846);
348 }
349}