pxfm 0.1.29

Fast and accurate math
Documentation
/*
 * // Copyright (c) Radzivon Bartoshyk 6/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_polyeval5;
use crate::tangent::evalf::tanf_eval;

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

    // |x| < pi/32
    if x_abs <= 0x3dc9_0fdbu32 {
        // |x| < 0.000244141
        if x_abs < 0x3980_0000u32 {
            if x_abs == 0 {
                return x;
            }

            // When |x| < 2^-12, the relative error of the approximation tan(x) ~ x
            // is:
            //   |tan(x) - x| / |tan(x)| < |x^3| / (3|x|)
            //                           = x^2 / 3
            //                           < 2^-25
            //                           < epsilon(1)/2.
            #[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, f32::from_bits(0xb3000000), x);
            }
            #[cfg(not(any(
                all(
                    any(target_arch = "x86", target_arch = "x86_64"),
                    target_feature = "fma"
                ),
                target_arch = "aarch64"
            )))]
            {
                return f_fmla(xd, f64::from_bits(0xbe60000000000000), xd) as f32;
            }
        }

        let xsqr = xd * xd;

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

           See ./notes/tanf_at_zero.sollya
        */
        let p = f_polyeval5(
            xsqr,
            f64::from_bits(0x3ff0000000000000),
            f64::from_bits(0x3fd555555553d022),
            f64::from_bits(0x3fc111111ce442c1),
            f64::from_bits(0x3faba180a6bbdecd),
            f64::from_bits(0x3f969c0a88a0b71f),
        );
        return (xd * p) as f32;
    }

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

    // For |x| >= pi/32, we use the definition of tan(x) function:
    // tan(a+b) = (tan(a) + tan(b)) / (1 - tan(a)tan(b))
    // tanf_eval returns:
    // - rs.tan_y = tan(pi/32 * y)          -> tangent of the remainder
    // - rs.tan_k = tan(pi/32 * k)          -> tan of the main angle multiple
    let rs = tanf_eval(xd, x_abs);

    // Then computing tan through identities
    // num = tan(k*pi/32) + tan(y*pi/32)
    let num = rs.tan_y + rs.tan_k;
    // den = 1 - tan(k*pi/32) * tan(y*pi/32)
    let den = f_fmla(rs.tan_y, -rs.tan_k, 1.);
    (num / den) as f32
}

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

    // |x| < pi/32
    if x_abs <= 0x3dc9_0fdbu32 {
        // |x| < 0.000244141
        if x_abs < 0x3980_0000u32 {
            if x_abs == 0 {
                return x;
            }

            // When |x| < 2^-12, the relative error of the approximation tan(x) ~ x
            // is:
            //   |tan(x) - x| / |tan(x)| < |x^3| / (3|x|)
            //                           = x^2 / 3
            //                           < 2^-25
            //                           < epsilon(1)/2.
            return f32::mul_add(x, f32::from_bits(0xb3000000), x);
        }

        let xsqr = xd * xd;

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

           See ./notes/tanf_at_zero.sollya
        */
        use crate::polyeval::d_polyeval5;
        let p = d_polyeval5(
            xsqr,
            f64::from_bits(0x3ff0000000000000),
            f64::from_bits(0x3fd555555553d022),
            f64::from_bits(0x3fc111111ce442c1),
            f64::from_bits(0x3faba180a6bbdecd),
            f64::from_bits(0x3f969c0a88a0b71f),
        );
        return (xd * p) as f32;
    }

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

    // For |x| >= pi/32, we use the definition of tan(x) function:
    // tan(a+b) = (tan(a) + tan(b)) / (1 - tan(a)tan(b))
    // tanf_eval returns:
    // - rs.tan_y = tan(pi/32 * y)          -> tangent of the remainder
    // - rs.tan_k = tan(pi/32 * k)          -> tan of the main angle multiple
    use crate::tangent::evalf::tanf_eval_fma;
    let rs = tanf_eval_fma(xd, x_abs);

    // Then computing tan through identities
    // num = tan(k*pi/32) + tan(y*pi/32)
    let num = rs.tan_y + rs.tan_k;
    // den = 1 - tan(k*pi/32) * tan(y*pi/32)
    let den = f64::mul_add(rs.tan_y, -rs.tan_k, 1.);
    (num / den) as f32
}

/// Computes tan
///
/// Max found ULP 0.4999999
#[inline]
pub fn f_tanf(x: f32) -> f32 {
    #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
    {
        tanf_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")
            {
                tanf_fma_impl
            } else {
                tanf_gen_impl
            }
        });
        unsafe { q(x) }
    }
}

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

    #[test]
    fn f_tanf_test() {
        assert_eq!(f_tanf(0.0), 0.0);
        assert_eq!(f_tanf(1.0), 1.5574077);
        assert_eq!(f_tanf(-1.0), -1.5574077);
        assert_eq!(f_tanf(10.0), 0.64836085);
        assert_eq!(f_tanf(-10.0), -0.64836085);
    }
}