pxfm 0.1.28

Fast and accurate math
Documentation
/*
 * // Copyright (c) Radzivon Bartoshyk 8/2025. All rights reserved.
 * //
 * // Redistribution and use in source and binary forms, with or without modification,
 * // are permitted provided that the following conditions are met:
 * //
 * // 1.  Redistributions of source code must retain the above copyright notice, this
 * // list of conditions and the following disclaimer.
 * //
 * // 2.  Redistributions in binary form must reproduce the above copyright notice,
 * // this list of conditions and the following disclaimer in the documentation
 * // and/or other materials provided with the distribution.
 * //
 * // 3.  Neither the name of the copyright holder nor the names of its
 * // contributors may be used to endorse or promote products derived from
 * // this software without specific prior written permission.
 * //
 * // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
use crate::common::f_fmla;
use crate::polyeval::f_polyeval6;
use crate::sin_cosf::sincosf_eval::sincosf_eval;

#[inline(always)]
fn secf_gen_impl(x: f32) -> f32 {
    let x_abs = x.to_bits() & 0x7fff_ffffu32;
    let x = f32::from_bits(x_abs);
    let xd = x as f64;

    // |x| <= pi/16
    if x_abs <= 0x3e49_0fdbu32 {
        // |x| < 0.000244141
        if x_abs < 0x3980_0000u32 {
            // taylor series for sec(x) ~ 1 + x^2/2 + O(x^4)
            // for such small interval just doing 2 first coefficients from taylor series
            // FMA availability is mandatory to perform it in f32 without upcasting to f64.
            #[cfg(any(
                all(
                    any(target_arch = "x86", target_arch = "x86_64"),
                    target_feature = "fma"
                ),
                target_arch = "aarch64"
            ))]
            {
                use crate::common::f_fmlaf;
                return f_fmlaf(x, x * f32::from_bits(0x3f000000), 1.);
            }
            #[cfg(not(any(
                all(
                    any(target_arch = "x86", target_arch = "x86_64"),
                    target_feature = "fma"
                ),
                target_arch = "aarch64"
            )))]
            {
                let x2 = xd * xd;
                return f_fmla(x2, f64::from_bits(0x3fe0000000000000), 1.) as f32;
            }
        }

        // Secant
        // Generated poly by Sollya:
        // f = 1 / cos(x);
        // d = [0.000244141; pi/16];
        // pf = fpminimax(f, [|0, 2, 4, 6, 8, 10|], [|1, D...|], d, relative, floating);
        //
        // See ./notes/secf.sollya

        let x2 = xd * xd;
        let p = f_polyeval6(
            x2,
            f64::from_bits(0x3ff0000000000000),
            f64::from_bits(0x3fe000000001c0fb),
            f64::from_bits(0x3fcaaaaaa0b8a71b),
            f64::from_bits(0x3fb5b06437bc5a13),
            f64::from_bits(0x3fa192a33a9fca4f),
            f64::from_bits(0x3f8dde280c29af37),
        );
        return p as f32;
    }

    if x_abs >= 0x7f80_0000u32 {
        return x + f32::NAN;
    }

    // Formula:
    //   cos(x) = cos((k + y)*pi/32)
    //          = cos(y*pi/32) * cos(k*pi/32) - sin(y*pi/32) * sin(k*pi/32)
    // The values of sin(k*pi/32) and cos(k*pi/32) for k = 0..63 are precomputed
    // and stored using a vector of 32 doubles. Sin(y*pi/32) and cos(y*pi/32) are
    // computed using degree-7 and degree-6 minimax polynomials generated by
    // Sollya respectively.
    // Combine the results with the sine of sum formula:
    //   cos(x) = cos((k + y)*pi/32)
    //          = cos(y*pi/32) * cos(k*pi/32) - sin(y*pi/32) * sin(k*pi/32)
    //          = cosm1_y * cos_k + sin_y * sin_k
    //          = (cosm1_y * cos_k + cos_k) + sin_y * sin_k
    // then sec(x) = 1/cos(x)

    let rs = sincosf_eval(xd, x_abs);
    (1. / f_fmla(rs.sin_y, -rs.sin_k, f_fmla(rs.cosm1_y, rs.cos_k, rs.cos_k))) as f32
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[target_feature(enable = "avx", enable = "fma")]
unsafe fn secf_fma_impl(x: f32) -> f32 {
    let x_abs = x.to_bits() & 0x7fff_ffffu32;
    let x = f32::from_bits(x_abs);
    let xd = x as f64;

    // |x| <= pi/16
    if x_abs <= 0x3e49_0fdbu32 {
        // |x| < 0.000244141
        if x_abs < 0x3980_0000u32 {
            // taylor series for sec(x) ~ 1 + x^2/2 + O(x^4)
            // for such small interval just doing 2 first coefficients from taylor series
            // FMA availability is mandatory to perform it in f32 without upcasting to f64.
            return f32::mul_add(x, x * f32::from_bits(0x3f000000), 1.);
        }

        // Secant
        // Generated poly by Sollya:
        // f = 1 / cos(x);
        // d = [0.000244141; pi/16];
        // pf = fpminimax(f, [|0, 2, 4, 6, 8, 10|], [|1, D...|], d, relative, floating);
        //
        // See ./notes/secf.sollya

        let x2 = xd * xd;
        use crate::polyeval::d_polyeval6;
        let p = d_polyeval6(
            x2,
            f64::from_bits(0x3ff0000000000000),
            f64::from_bits(0x3fe000000001c0fb),
            f64::from_bits(0x3fcaaaaaa0b8a71b),
            f64::from_bits(0x3fb5b06437bc5a13),
            f64::from_bits(0x3fa192a33a9fca4f),
            f64::from_bits(0x3f8dde280c29af37),
        );
        return p as f32;
    }

    if x_abs >= 0x7f80_0000u32 {
        return x + f32::NAN;
    }

    // Formula:
    //   cos(x) = cos((k + y)*pi/32)
    //          = cos(y*pi/32) * cos(k*pi/32) - sin(y*pi/32) * sin(k*pi/32)
    // The values of sin(k*pi/32) and cos(k*pi/32) for k = 0..63 are precomputed
    // and stored using a vector of 32 doubles. Sin(y*pi/32) and cos(y*pi/32) are
    // computed using degree-7 and degree-6 minimax polynomials generated by
    // Sollya respectively.
    // Combine the results with the sine of sum formula:
    //   cos(x) = cos((k + y)*pi/32)
    //          = cos(y*pi/32) * cos(k*pi/32) - sin(y*pi/32) * sin(k*pi/32)
    //          = cosm1_y * cos_k + sin_y * sin_k
    //          = (cosm1_y * cos_k + cos_k) + sin_y * sin_k
    // then sec(x) = 1/cos(x)
    use crate::sin_cosf::sincosf_eval::sincosf_eval_fma;
    let rs = sincosf_eval_fma(xd, x_abs);
    (1. / f64::mul_add(
        rs.sin_y,
        -rs.sin_k,
        f64::mul_add(rs.cosm1_y, rs.cos_k, rs.cos_k),
    )) as f32
}

/// Computes secant ( 1 / cos(x) )
///
/// Max found ULP 0.5
#[inline]
pub fn f_secf(x: f32) -> f32 {
    #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
    {
        secf_gen_impl(x)
    }
    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    {
        use std::sync::OnceLock;
        static EXECUTOR: OnceLock<unsafe fn(f32) -> f32> = OnceLock::new();
        let q = EXECUTOR.get_or_init(|| {
            if std::arch::is_x86_feature_detected!("avx")
                && std::arch::is_x86_feature_detected!("fma")
            {
                secf_fma_impl
            } else {
                secf_gen_impl
            }
        });
        unsafe { q(x) }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_f_secf() {
        assert_eq!(f_secf(0.0), 1.0);
        assert_eq!(f_secf(0.5), 1.139494);
        assert_eq!(f_secf(-0.5), 1.139494);
        assert_eq!(f_secf(1.5), 14.136833);
        assert_eq!(f_secf(-1.5), 14.136833);
        assert!(f_secf(f32::INFINITY).is_nan());
        assert!(f_secf(f32::NEG_INFINITY).is_nan());
        assert!(f_secf(f32::NAN).is_nan());
    }
}