pxfm 0.1.29

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_estrin_polyeval5;
use crate::sin_cosf::sincosf_eval::sincosf_eval;

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

    // |x| <= pi/16
    if x_abs <= 0x3e49_0fdbu32 {
        // |x| < 0.000443633
        if x_abs < 0x3980_0000u32 {
            if x_abs == 0u32 {
                // For signed zeros.
                return (x, 1.0);
            }
            #[cfg(any(
                all(
                    any(target_arch = "x86", target_arch = "x86_64"),
                    target_feature = "fma"
                ),
                target_arch = "aarch64"
            ))]
            {
                use crate::common::f_fmlaf;
                let sf = f_fmlaf(x, f32::from_bits(0xb3000000), x);
                let cf = f_fmlaf(f32::from_bits(x_abs), f32::from_bits(0xb3000000), 1.);
                return (sf, cf);
            }
            #[cfg(not(any(
                all(
                    any(target_arch = "x86", target_arch = "x86_64"),
                    target_feature = "fma"
                ),
                target_arch = "aarch64"
            )))]
            {
                let sf = f_fmla(xd, f64::from_bits(0xbe60000000000000), xd) as f32;
                let cf = f_fmla(xd, f64::from_bits(0xbe60000000000000), 1.) as f32;
                return (sf, cf);
            }
        }

        let xsqr = xd * xd;

        /*
        Generated by Sollya:
        f_sinpi_16 = sin(x)/x;
        Q = fpminimax(f_sinpi_16, [|0, 2, 4, 6, 8|], [|1, D...|], [0, pi/16]);

        See ./notes/sincosf.sollya
         */
        let p = f_estrin_polyeval5(
            xsqr,
            f64::from_bits(0x3ff0000000000000),
            f64::from_bits(0xbfc55555555554c6),
            f64::from_bits(0x3f81111111085e65),
            f64::from_bits(0xbf2a019f70fb4d4f),
            f64::from_bits(0x3ec718d179815e74),
        );
        let sf = (xd * p) as f32;

        // Cosine
        // Generated poly by Sollya:
        // f_cos_16 = cos(x);
        //
        // Q = fpminimax(f_cos_16, [|0, 2, 4, 6, 8|], [|1, D...|], [0, pi/16]);
        let cf = f_estrin_polyeval5(
            xsqr,
            f64::from_bits(0x3ff0000000000000),
            f64::from_bits(0xbfdffffffffffcea),
            f64::from_bits(0x3fa55555553d611a),
            f64::from_bits(0xbf56c16b2e26561a),
            f64::from_bits(0x3ef9faa67b9da80b),
        );
        return (sf, cf as f32);
    }

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

    // Formula:
    //   sin(x) = sin((k + y)*pi/32)
    //          = sin(y*pi/32) * cos(k*pi/32) + cos(y*pi/32) * sin(k*pi/32)
    // The values of sin(k*pi/32) and cos(k*pi/32) for k = 0..31 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.

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

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

    // |x| <= pi/16
    if x_abs <= 0x3e49_0fdbu32 {
        // |x| < 0.000443633
        if x_abs < 0x3980_0000u32 {
            if x_abs == 0u32 {
                // For signed zeros.
                return (x, 1.0);
            }
            let sf = f32::mul_add(x, f32::from_bits(0xb3000000), x);
            let cf = f32::mul_add(f32::from_bits(x_abs), f32::from_bits(0xb3000000), 1.);
            return (sf, cf);
        }

        let xsqr = xd * xd;

        /*
        Generated by Sollya:
        f_sinpi_16 = sin(x)/x;
        Q = fpminimax(f_sinpi_16, [|0, 2, 4, 6, 8|], [|1, D...|], [0, pi/16]);

        See ./notes/sincosf.sollya
         */
        use crate::polyeval::d_estrin_polyeval5;
        let p = d_estrin_polyeval5(
            xsqr,
            f64::from_bits(0x3ff0000000000000),
            f64::from_bits(0xbfc55555555554c6),
            f64::from_bits(0x3f81111111085e65),
            f64::from_bits(0xbf2a019f70fb4d4f),
            f64::from_bits(0x3ec718d179815e74),
        );
        let sf = (xd * p) as f32;

        // Cosine
        // Generated poly by Sollya:
        // f_cos_16 = cos(x);
        //
        // Q = fpminimax(f_cos_16, [|0, 2, 4, 6, 8|], [|1, D...|], [0, pi/16]);
        let cf = d_estrin_polyeval5(
            xsqr,
            f64::from_bits(0x3ff0000000000000),
            f64::from_bits(0xbfdffffffffffcea),
            f64::from_bits(0x3fa55555553d611a),
            f64::from_bits(0xbf56c16b2e26561a),
            f64::from_bits(0x3ef9faa67b9da80b),
        );
        return (sf, cf as f32);
    }

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

    // Formula:
    //   sin(x) = sin((k + y)*pi/32)
    //          = sin(y*pi/32) * cos(k*pi/32) + cos(y*pi/32) * sin(k*pi/32)
    // The values of sin(k*pi/32) and cos(k*pi/32) for k = 0..31 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.

    use crate::sin_cosf::sincosf_eval::sincosf_eval_fma;
    let rs = sincosf_eval_fma(xd, x_abs);
    let sf = f64::mul_add(
        rs.sin_y,
        rs.cos_k,
        f64::mul_add(rs.cosm1_y, rs.sin_k, rs.sin_k),
    ) as f32;
    let cf = f64::mul_add(
        rs.sin_y,
        -rs.sin_k,
        f64::mul_add(rs.cosm1_y, rs.cos_k, rs.cos_k),
    ) as f32;
    (sf, cf)
}

/// Sine and cosine
///
/// Max found ULP on working range 0.49999967
#[inline]
pub fn f_sincosf(x: f32) -> (f32, f32) {
    #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
    {
        sincosf_gen_impl(x)
    }
    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    {
        use std::sync::OnceLock;
        static EXECUTOR: OnceLock<unsafe fn(f32) -> (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")
            {
                sincosf_fma_impl
            } else {
                sincosf_gen_impl
            }
        });
        unsafe { q(x) }
    }
}

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

    #[test]
    fn f_sincosf_test() {
        let sincos0 = f_sincosf(0.0);
        assert!(sincos0.0 < 1e-8);
        assert_eq!(sincos0.1, 1.0);
        let sincos_pi = f_sincosf(std::f32::consts::PI);
        assert!(sincos_pi.0 < 1e-8);
        let sincos_pi_0_5 = f_sincosf(0.5);
        assert_eq!(sincos_pi_0_5.0, 0.47942555);
        assert_eq!(sincos_pi_0_5.1, 0.87758255);
        let sincos_pi_n0_5 = f_sincosf(-0.5);
        assert_eq!(sincos_pi_n0_5.0, -0.47942555);
        assert_eq!(sincos_pi_n0_5.1, 0.87758255);
        let v_z = f_sincosf(0.0002480338);
        assert_eq!(v_z.1, 0.9999999692396206);
    }

    #[test]
    fn f_sincosf_edge_test() {
        let s0 = f_sincosf(f32::INFINITY);
        assert!(s0.0.is_nan());
        assert!(s0.1.is_nan());
        let s1 = f_sincosf(f32::NEG_INFINITY);
        assert!(s1.0.is_nan());
        assert!(s1.1.is_nan());
        let s2 = f_sincosf(f32::NAN);
        assert!(s2.0.is_nan());
        assert!(s2.1.is_nan());
    }
}