pxfm/
acospi.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::asin::asin_eval;
30use crate::asin_eval_dyadic::asin_eval_dyadic;
31use crate::common::f_fmla;
32use crate::double_double::DoubleDouble;
33use crate::dyadic_float::{DyadicFloat128, DyadicSign};
34use crate::round::RoundFinite;
35
36pub(crate) const INV_PI_DD: DoubleDouble = DoubleDouble::new(
37    f64::from_bits(0xbc76b01ec5417056),
38    f64::from_bits(0x3fd45f306dc9c883),
39);
40
41// 1/PI with 128-bit precision generated by SageMath with:
42// def format_hex(value):
43//     l = hex(value)[2:]
44//     n = 8
45//     x = [l[i:i + n] for i in range(0, len(l), n)]
46//     return "0x" + "'".join(x) + "_u128"
47//  r = 1/pi
48//  (s, m, e) = RealField(128)(r).sign_mantissa_exponent();
49//  print(format_hex(m));
50pub(crate) const INV_PI_F128: DyadicFloat128 = DyadicFloat128 {
51    sign: DyadicSign::Pos,
52    exponent: -129,
53    mantissa: 0xa2f9836e_4e441529_fc2757d1_f534ddc1_u128,
54};
55
56pub(crate) const PI_OVER_TWO_F128: DyadicFloat128 = DyadicFloat128 {
57    sign: DyadicSign::Pos,
58    exponent: -127,
59    mantissa: 0xc90fdaa2_2168c234_c4c6628b_80dc1cd1_u128,
60};
61
62/// Computes acos(x)/PI
63///
64/// Max ULP 0.5
65pub fn f_acospi(x: f64) -> f64 {
66    let x_e = (x.to_bits() >> 52) & 0x7ff;
67    const E_BIAS: u64 = (1u64 << (11 - 1u64)) - 1u64;
68
69    const PI_OVER_TWO: DoubleDouble = DoubleDouble::new(
70        f64::from_bits(0x3c91a62633145c07),
71        f64::from_bits(0x3ff921fb54442d18),
72    );
73
74    let x_abs = f64::from_bits(x.to_bits() & 0x7fff_ffff_ffff_ffff);
75
76    // |x| < 0.5.
77    if x_e < E_BIAS - 1 {
78        // |x| < 2^-55.
79        if x_e < E_BIAS - 55 {
80            // When |x| < 2^-55, acos(x) = pi/2
81            return f_fmla(f64::from_bits(0xbc80000000000000), x, 0.5);
82        }
83
84        let x_sq = DoubleDouble::from_exact_mult(x, x);
85        let err = x_abs * f64::from_bits(0x3cc0000000000000);
86        // Polynomial approximation:
87        //   p ~ asin(x)/x
88        let (p, err) = asin_eval(x_sq, err);
89        // asin(x) ~ x * p
90        let r0 = DoubleDouble::from_exact_mult(x, p.hi);
91        // acos(x) = pi/2 - asin(x)
92        //         ~ pi/2 - x * p
93        //         = pi/2 - x * (p.hi + p.lo)
94        let mut r_hi = f_fmla(-x, p.hi, PI_OVER_TWO.hi);
95        // Use Dekker's 2SUM algorithm to compute the lower part.
96        let mut r_lo = ((PI_OVER_TWO.hi - r_hi) - r0.hi) - r0.lo;
97        r_lo = f_fmla(-x, p.lo, r_lo + PI_OVER_TWO.lo);
98
99        let p = DoubleDouble::mult(DoubleDouble::new(r_lo, r_hi), INV_PI_DD);
100        r_hi = p.hi;
101        r_lo = p.lo;
102
103        let r_upper = r_hi + (r_lo + err);
104        let r_lower = r_hi + (r_lo - err);
105
106        if r_upper == r_lower {
107            return r_upper;
108        }
109
110        // Ziv's accuracy test failed, perform 128-bit calculation.
111
112        // Recalculate mod 1/64.
113        let idx = (x_sq.hi * f64::from_bits(0x4050000000000000)).round_finite() as usize;
114
115        // Get x^2 - idx/64 exactly.  When FMA is available, double-double
116        // multiplication will be correct for all rounding modes. Otherwise, we use
117        // Float128 directly.
118        let mut x_f128 = DyadicFloat128::new_from_f64(x);
119
120        let u: DyadicFloat128;
121        #[cfg(any(
122            all(
123                any(target_arch = "x86", target_arch = "x86_64"),
124                target_feature = "fma"
125            ),
126            all(target_arch = "aarch64", target_feature = "neon")
127        ))]
128        {
129            // u = x^2 - idx/64
130            let u_hi = DyadicFloat128::new_from_f64(f_fmla(
131                idx as f64,
132                f64::from_bits(0xbf90000000000000),
133                x_sq.hi,
134            ));
135            u = u_hi.quick_add(&DyadicFloat128::new_from_f64(x_sq.lo));
136        }
137
138        #[cfg(not(any(
139            all(
140                any(target_arch = "x86", target_arch = "x86_64"),
141                target_feature = "fma"
142            ),
143            all(target_arch = "aarch64", target_feature = "neon")
144        )))]
145        {
146            let x_sq_f128 = x_f128.quick_mul(&x_f128);
147            u = x_sq_f128.quick_add(&DyadicFloat128::new_from_f64(
148                idx as f64 * f64::from_bits(0xbf90000000000000),
149            ));
150        }
151
152        let p_f128 = asin_eval_dyadic(u, idx);
153        // Flip the sign of x_f128 to perform subtraction.
154        x_f128.sign = x_f128.sign.negate();
155        let mut r = PI_OVER_TWO_F128.quick_add(&x_f128.quick_mul(&p_f128));
156        r = r.quick_mul(&INV_PI_F128);
157        return r.fast_as_f64();
158    }
159
160    // |x| >= 0.5
161
162    const PI: DoubleDouble = DoubleDouble::new(
163        f64::from_bits(0x3ca1a62633145c07),
164        f64::from_bits(0x400921fb54442d18),
165    );
166
167    // |x| >= 1
168    if x_e >= E_BIAS {
169        // x = +-1, asin(x) = +- pi/2
170        if x_abs == 1.0 {
171            // x = 1, acos(x) = 0,
172            // x = -1, acos(x) = pi
173            return if x == 1.0 { 0.0 } else { 1.0 };
174        }
175        // |x| > 1, return NaN.
176        return f64::NAN;
177    }
178
179    // When |x| >= 0.5, we perform range reduction as follow:
180    //
181    // When 0.5 <= x < 1, let:
182    //   y = acos(x)
183    // We will use the double angle formula:
184    //   cos(2y) = 1 - 2 sin^2(y)
185    // and the complement angle identity:
186    //   x = cos(y) = 1 - 2 sin^2 (y/2)
187    // So:
188    //   sin(y/2) = sqrt( (1 - x)/2 )
189    // And hence:
190    //   y/2 = asin( sqrt( (1 - x)/2 ) )
191    // Equivalently:
192    //   acos(x) = y = 2 * asin( sqrt( (1 - x)/2 ) )
193    // Let u = (1 - x)/2, then:
194    //   acos(x) = 2 * asin( sqrt(u) )
195    // Moreover, since 0.5 <= x < 1:
196    //   0 < u <= 1/4, and 0 < sqrt(u) <= 0.5,
197    // And hence we can reuse the same polynomial approximation of asin(x) when
198    // |x| <= 0.5:
199    //   acos(x) ~ 2 * sqrt(u) * P(u).
200    //
201    // When -1 < x <= -0.5, we reduce to the previous case using the formula:
202    //   acos(x) = pi - acos(-x)
203    //           = pi - 2 * asin ( sqrt( (1 + x)/2 ) )
204    //           ~ pi - 2 * sqrt(u) * P(u),
205    // where u = (1 - |x|)/2.
206
207    // u = (1 - |x|)/2
208    let u = f_fmla(x_abs, -0.5, 0.5);
209    // v_hi + v_lo ~ sqrt(u).
210    // Let:
211    //   h = u - v_hi^2 = (sqrt(u) - v_hi) * (sqrt(u) + v_hi)
212    // Then:
213    //   sqrt(u) = v_hi + h / (sqrt(u) + v_hi)
214    //            ~ v_hi + h / (2 * v_hi)
215    // So we can use:
216    //   v_lo = h / (2 * v_hi).
217    let v_hi = u.sqrt();
218
219    let h;
220    #[cfg(any(
221        all(
222            any(target_arch = "x86", target_arch = "x86_64"),
223            target_feature = "fma"
224        ),
225        all(target_arch = "aarch64", target_feature = "neon")
226    ))]
227    {
228        h = f_fmla(v_hi, -v_hi, u);
229    }
230    #[cfg(not(any(
231        all(
232            any(target_arch = "x86", target_arch = "x86_64"),
233            target_feature = "fma"
234        ),
235        all(target_arch = "aarch64", target_feature = "neon")
236    )))]
237    {
238        let v_hi_sq = DoubleDouble::from_exact_mult(v_hi, v_hi);
239        h = (u - v_hi_sq.hi) - v_hi_sq.lo;
240    }
241
242    // Scale v_lo and v_hi by 2 from the formula:
243    //   vh = v_hi * 2
244    //   vl = 2*v_lo = h / v_hi.
245    let vh = v_hi * 2.0;
246    let vl = h / v_hi;
247
248    // Polynomial approximation:
249    //   p ~ asin(sqrt(u))/sqrt(u)
250    let err = vh * f64::from_bits(0x3cc0000000000000);
251
252    let (p, err) = asin_eval(DoubleDouble::new(0.0, u), err);
253
254    // Perform computations in double-double arithmetic:
255    //   asin(x) = pi/2 - (v_hi + v_lo) * (ASIN_COEFFS[idx][0] + p)
256    let r0 = DoubleDouble::quick_mult(DoubleDouble::new(vl, vh), p);
257
258    let mut r_hi;
259    let mut r_lo;
260    if x.is_sign_positive() {
261        r_hi = r0.hi;
262        r_lo = r0.lo;
263    } else {
264        let r = DoubleDouble::from_exact_add(PI.hi, -r0.hi);
265        r_hi = r.hi;
266        r_lo = (PI.lo - r0.lo) + r.lo;
267    }
268
269    let p = DoubleDouble::mult(DoubleDouble::new(r_lo, r_hi), INV_PI_DD);
270    r_hi = p.hi;
271    r_lo = p.lo;
272
273    let r_upper = r_hi + (r_lo + err);
274    let r_lower = r_hi + (r_lo - err);
275
276    if r_upper == r_lower {
277        return r_upper;
278    }
279
280    // Ziv's accuracy test failed, we redo the computations in Float128.
281    // Recalculate mod 1/64.
282    let idx = (u * f64::from_bits(0x4050000000000000)).round_finite() as usize;
283
284    // After the first step of Newton-Raphson approximating v = sqrt(u), we have
285    // that:
286    //   sqrt(u) = v_hi + h / (sqrt(u) + v_hi)
287    //      v_lo = h / (2 * v_hi)
288    // With error:
289    //   sqrt(u) - (v_hi + v_lo) = h * ( 1/(sqrt(u) + v_hi) - 1/(2*v_hi) )
290    //                           = -h^2 / (2*v * (sqrt(u) + v)^2).
291    // Since:
292    //   (sqrt(u) + v_hi)^2 ~ (2sqrt(u))^2 = 4u,
293    // we can add another correction term to (v_hi + v_lo) that is:
294    //   v_ll = -h^2 / (2*v_hi * 4u)
295    //        = -v_lo * (h / 4u)
296    //        = -vl * (h / 8u),
297    // making the errors:
298    //   sqrt(u) - (v_hi + v_lo + v_ll) = O(h^3)
299    // well beyond 128-bit precision needed.
300
301    // Get the rounding error of vl = 2 * v_lo ~ h / vh
302    // Get full product of vh * vl
303    let vl_lo;
304    #[cfg(any(
305        all(
306            any(target_arch = "x86", target_arch = "x86_64"),
307            target_feature = "fma"
308        ),
309        all(target_arch = "aarch64", target_feature = "neon")
310    ))]
311    {
312        vl_lo = f_fmla(-v_hi, vl, h) / v_hi;
313    }
314    #[cfg(not(any(
315        all(
316            any(target_arch = "x86", target_arch = "x86_64"),
317            target_feature = "fma"
318        ),
319        all(target_arch = "aarch64", target_feature = "neon")
320    )))]
321    {
322        let vh_vl = DoubleDouble::from_exact_mult(v_hi, vl);
323        vl_lo = ((h - vh_vl.hi) - vh_vl.lo) / v_hi;
324    }
325    let t = h * (-0.25) / u;
326    let vll = f_fmla(vl, t, vl_lo);
327    // m_v = -(v_hi + v_lo + v_ll).
328    let m_v_p = DyadicFloat128::new_from_f64(vl) + DyadicFloat128::new_from_f64(vll);
329    let mut m_v = DyadicFloat128::new_from_f64(vh) + m_v_p;
330    m_v.sign = if x.is_sign_negative() {
331        DyadicSign::Neg
332    } else {
333        DyadicSign::Pos
334    };
335
336    // Perform computations in Float128:
337    //   acos(x) = (v_hi + v_lo + vll) * P(u)         , when 0.5 <= x < 1,
338    //           = pi - (v_hi + v_lo + vll) * P(u)    , when -1 < x <= -0.5.
339    let y_f128 =
340        DyadicFloat128::new_from_f64(f_fmla(idx as f64, f64::from_bits(0xbf90000000000000), u));
341
342    let p_f128 = asin_eval_dyadic(y_f128, idx);
343    let mut r_f128 = m_v * p_f128;
344
345    if x.is_sign_negative() {
346        const PI_F128: DyadicFloat128 = DyadicFloat128 {
347            sign: DyadicSign::Pos,
348            exponent: -126,
349            mantissa: 0xc90fdaa2_2168c234_c4c6628b_80dc1cd1_u128,
350        };
351        r_f128 = PI_F128 + r_f128;
352    }
353
354    r_f128 = r_f128.quick_mul(&INV_PI_F128);
355
356    r_f128.fast_as_f64()
357}
358
359#[cfg(test)]
360mod tests {
361
362    use super::*;
363
364    #[test]
365    fn acospi_test() {
366        assert_eq!(f_acospi(0.5), 0.3333333333333333);
367        assert!(f_acospi(1.5).is_nan());
368    }
369}