pxfm/
sec.rs

1/*
2 * // Copyright (c) Radzivon Bartoshyk 7/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::sin::{get_sin_k_rational, range_reduction_small, sincos_eval};
32use crate::sin_table::SIN_K_PI_OVER_128;
33use crate::sincos_dyadic::{range_reduction_small_f128, sincos_eval_dyadic};
34use crate::sincos_reduce::LargeArgumentReduction;
35
36#[cold]
37fn sec_accurate(x: f64, argument_reduction: &mut LargeArgumentReduction, x_e: u64, k: u64) -> f64 {
38    const EXP_BIAS: u64 = (1u64 << (11 - 1u64)) - 1u64;
39    let u_f128 = if x_e < EXP_BIAS + 16 {
40        range_reduction_small_f128(x)
41    } else {
42        argument_reduction.accurate()
43    };
44
45    let sin_cos = sincos_eval_dyadic(&u_f128);
46
47    // -sin(k * pi/128) = sin((k + 128) * pi/128)
48    // cos(k * pi/128) = sin(k * pi/128 + pi/2) = sin((k + 64) * pi/128).
49    let msin_k_f128 = get_sin_k_rational(k.wrapping_add(128));
50    let cos_k_f128 = get_sin_k_rational(k.wrapping_add(64));
51
52    // cos(x) = cos((k * pi/128 + u)
53    //        = cos(u) * cos(k*pi/128) - sin(u) * sin(k*pi/128)
54    let r = (cos_k_f128 * sin_cos.v_cos) + (msin_k_f128 * sin_cos.v_sin);
55    r.reciprocal().fast_as_f64()
56}
57
58/// Secant for double precision
59///
60/// ULP 0.5
61pub fn f_sec(x: f64) -> f64 {
62    let x_e = (x.to_bits() >> 52) & 0x7ff;
63    const E_BIAS: u64 = (1u64 << (11 - 1u64)) - 1u64;
64
65    let y: DoubleDouble;
66    let k;
67
68    let mut argument_reduction = LargeArgumentReduction::default();
69
70    if x_e < E_BIAS + 16 {
71        // |x| < 2^32 (with FMA) or |x| < 2^23 (w/o FMA)
72        if x_e < E_BIAS - 7 {
73            // |x| < 2^-7
74            if x_e < E_BIAS - 27 {
75                // |x| < 2^-27
76                if x == 0.0 {
77                    // Signed zeros.
78                    return 1.0;
79                }
80                // taylor series for sec(x) ~ 1 + x^2/2 + O(x^4)
81                return f_fmla(x, x * 0.5, 1.);
82            }
83            k = 0;
84            y = DoubleDouble::new(0.0, x);
85        } else {
86            // Small range reduction.
87            (y, k) = range_reduction_small(x);
88        }
89    } else {
90        // Inf or NaN
91        if x_e > 2 * E_BIAS {
92            // sec(+-Inf) = NaN
93            return x + f64::NAN;
94        }
95
96        // Large range reduction.
97        (k, y) = argument_reduction.reduce(x);
98    }
99    let r_sincos = sincos_eval(y);
100
101    // Fast look up version, but needs 256-entry table.
102    // cos(k * pi/128) = sin(k * pi/128 + pi/2) = sin((k + 64) * pi/128).
103    let sk = SIN_K_PI_OVER_128[(k.wrapping_add(128) & 255) as usize];
104    let ck = SIN_K_PI_OVER_128[((k.wrapping_add(64)) & 255) as usize];
105    let msin_k = DoubleDouble::from_bit_pair(sk);
106    let cos_k = DoubleDouble::from_bit_pair(ck);
107
108    let cos_k_cos_y = DoubleDouble::quick_mult(r_sincos.v_cos, cos_k);
109    let cos_k_msin_y = DoubleDouble::quick_mult(r_sincos.v_sin, msin_k);
110
111    // cos_k_cos_y is always >> cos_k_msin_y
112    let mut rr = DoubleDouble::from_exact_add(cos_k_cos_y.hi, cos_k_msin_y.hi);
113    rr.lo += cos_k_cos_y.lo + cos_k_msin_y.lo;
114
115    rr = DoubleDouble::from_exact_add(rr.hi, rr.lo);
116    rr = rr.recip();
117
118    let rlp = rr.lo + r_sincos.err;
119    let rlm = rr.lo - r_sincos.err;
120
121    let r_upper = rr.hi + rlp; // (rr.lo + ERR);
122    let r_lower = rr.hi + rlm; // (rr.lo - ERR);
123
124    // Ziv's accuracy test
125    if r_upper == r_lower {
126        return rr.to_f64();
127    }
128
129    sec_accurate(x, &mut argument_reduction, x_e, k)
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    #[test]
137    fn test_sec() {
138        assert_eq!(f_sec(-175432.), 1.461049620895326);
139        assert_eq!(f_sec(175432.), 1.461049620895326);
140        assert_eq!(f_sec(-10.), -1.1917935066878957);
141        assert_eq!(f_sec(10.), -1.1917935066878957);
142        assert_eq!(f_sec(5.), 3.5253200858160882);
143        assert_eq!(f_sec(-5.), 3.5253200858160882);
144        assert_eq!(f_sec(0.), 1.0);
145        assert!(f_sec(f64::NAN).is_nan());
146        assert!(f_sec(f64::INFINITY).is_nan());
147        assert!(f_sec(f64::NEG_INFINITY).is_nan());
148    }
149}