pxfm/cube_roots/
rcbrt.rs

1/*
2 * // Copyright (c) Radzivon Bartoshyk 8/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::common::f_fmla;
30use crate::double_double::DoubleDouble;
31use crate::exponents::fast_ldexp;
32use crate::polyeval::f_polyeval6;
33
34//
35// // y1 = y0 + 1/3 * y0 * (1 - a * y0 * y0 * y0)
36// #[inline]
37// fn raphson_step(x: f64, a: f64) -> f64 {
38//     let h = f_fmla(-a * x, x * x, 1.0);
39//     f_fmla(1. / 3. * h, x, x)
40// }
41
42// y1 = y0(k1 − c(k2 − k3c), c = x*y0*y0*y0
43// k1 = 14/9 , k2 = 7/9 , k3 = 2/9
44#[inline(always)]
45fn halleys_div_free(x: f64, a: f64) -> f64 {
46    const K3: f64 = 2. / 9.;
47    const K2: f64 = 7. / 9.;
48    const K1: f64 = 14. / 9.;
49    let c = a * x * x * x;
50    let mut y = f_fmla(-K3, c, K2);
51    y = f_fmla(-c, y, K1);
52    y * x
53}
54
55/// Computes 1/cbrt(x)
56///
57/// ULP 0.5
58pub fn f_rcbrt(a: f64) -> f64 {
59    // Decompose a = m * 2^e, with m in [0.5, 1)
60    let xu = a.to_bits();
61    let exp = ((xu >> 52) & 0x7ff) as i32;
62    let mut e = ((xu >> 52) & 0x7ff) as i32;
63    let mut mant = xu & ((1u64 << 52) - 1);
64
65    if exp == 0x7ff {
66        if a.is_infinite() {
67            return if a.is_sign_negative() { -0.0 } else { 0.0 };
68        }
69        return a + a;
70    }
71    if exp == 0 && a == 0. {
72        return if a.is_sign_negative() {
73            f64::NEG_INFINITY
74        } else {
75            f64::INFINITY
76        };
77    }
78
79    // Normalize subnormal
80    if exp == 0 {
81        let norm = a * f64::from_bits(0x4350000000000000); // * 2^54
82        let norm_bits = norm.to_bits();
83        mant = norm_bits & ((1u64 << 52) - 1);
84        e = ((norm_bits >> 52) & 0x7ff) as i32 - 54;
85    }
86
87    e -= 1023;
88
89    mant |= 0x3ff << 52;
90    let m = f64::from_bits(mant);
91
92    // Polynomial for x^(-1/3) on [1.0; 2.0]
93    // Generated by Sollya:
94    // d = [1.0, 2.0];
95    // f_inv_cbrt = x^(-1/3);
96    // Q = fpminimax(f_inv_cbrt, 5, [|D...|], d, relative, floating);
97    // See ./notes/inv_cbrt.sollya
98
99    let p = f_polyeval6(
100        m,
101        f64::from_bits(0x3ffc7f365bceaf71),
102        f64::from_bits(0xbff90e741fb9c896),
103        f64::from_bits(0x3ff3e68b9b2cd237),
104        f64::from_bits(0xbfe321c5eb24a185),
105        f64::from_bits(0x3fc3fa269b897f69),
106        f64::from_bits(0xbf916d6f13849fd1),
107    );
108
109    // split exponent e = 3*q + r with r in {0,1,2}
110    // use div_euclid/rem_euclid to get r >= 0
111    let q = e.div_euclid(3);
112    let rem_scale = e.rem_euclid(3);
113
114    // 1; 2^{-1/3}; 2^{-2/3}
115    static ESCALE: [u64; 3] = [1.0f64.to_bits(), 0x3fe965fea53d6e3d, 0x3fe428a2f98d728b];
116
117    let z = p * f64::from_bits(ESCALE[rem_scale as usize]);
118
119    let mm = fast_ldexp(m, rem_scale); // bring domain into [1;8]
120
121    // One Halley's method step
122    // then refine in partial double-double precision with Newton-Raphson iteration
123    let y0 = halleys_div_free(z, mm);
124
125    let d2y = DoubleDouble::from_exact_mult(y0, y0);
126    let d3y = DoubleDouble::quick_mult_f64(d2y, y0);
127    let hb = DoubleDouble::quick_mult_f64(d3y, mm);
128
129    let y: f64;
130
131    #[cfg(any(
132        all(
133            any(target_arch = "x86", target_arch = "x86_64"),
134            target_feature = "fma"
135        ),
136        all(target_arch = "aarch64", target_feature = "neon")
137    ))]
138    {
139        // decompose double-double in linear FMA sums
140        // r = (1.0 - hb.hi - hb.lo) * y0 = y0 - hb.hi * y0 - hb.lo * y0 = fma(-hb.lo, y0, fma(-hb.hi, y0, y0))
141        let r = f_fmla(-hb.lo, y0, f_fmla(hb.hi, -y0, y0));
142        // // y1 = y0 + 1/3 * y0 * (1 - a * y0 * y0 * y0) = y0 + 1/3 * r
143        y = f_fmla(1. / 3., r, y0);
144    }
145    #[cfg(not(any(
146        all(
147            any(target_arch = "x86", target_arch = "x86_64"),
148            target_feature = "fma"
149        ),
150        all(target_arch = "aarch64", target_feature = "neon")
151    )))]
152    {
153        let m_hb = DoubleDouble::full_add_f64(-hb, 1.0);
154        let r = DoubleDouble::quick_mult_f64(m_hb, y0);
155        y = f_fmla(1. / 3., r.to_f64(), y0);
156    }
157    f64::copysign(fast_ldexp(y, -q), a)
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    #[test]
165    fn test_rcbrt() {
166        assert_eq!(f_rcbrt(0.9999999999999717), 1.0000000000000095);
167        assert_eq!(f_rcbrt(-68355745214719140000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.),
168                   -0.000000000000000000000000000000000000000002445728958868668);
169        assert_eq!(f_rcbrt(-96105972807656840000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.),
170                   -0.0000000000000000000000000000000000000000000000000000000002183148143573148);
171        assert_eq!(f_rcbrt(0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000139491540182158),
172                   8949883389846071000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.);
173        assert_eq!(f_rcbrt(0.00008386280387617153), 22.846001824951983);
174        assert_eq!(f_rcbrt(-125.0), -0.2);
175        assert_eq!(f_rcbrt(125.0), 0.2);
176        assert_eq!(f_rcbrt(1.0), 1.0);
177        assert_eq!(f_rcbrt(-1.0), -1.0);
178        assert_eq!(f_rcbrt(0.0), f64::INFINITY);
179        assert_eq!(f_rcbrt(-27.0), -1. / 3.);
180        assert_eq!(
181            f_rcbrt(2417851639214765300000000.),
182            0.000000007450580596938716
183        );
184        assert_eq!(f_rcbrt(27.0), 1. / 3.);
185        assert_eq!(f_rcbrt(64.0), 0.25);
186        assert_eq!(f_rcbrt(-64.0), -0.25);
187        assert_eq!(f_rcbrt(f64::NEG_INFINITY), -0.0);
188        assert_eq!(f_rcbrt(f64::INFINITY), 0.0);
189        assert!(f_rcbrt(f64::NAN).is_nan());
190    }
191}